Vue.js what's the difference of $emit and $dispatch?

17,385

No, You will not be able to replace $disptach with $emit everywhere. You can replace it, wherever you are using it for communication from child to parent, but for other cases, you may have to take some other approach.

From the documentation ( similar comments from Evan you in Upgrade Tips):

One of the most common uses for these methods is to communicate between a parent and its direct children. In these cases, you can actually listen to an $emit from a child with v-on. This allows you to keep the convenience of events with added explicitness.

However, when communicating between distant descendants/ancestors, $emit won’t help you. Instead, the simplest possible upgrade would be to use a centralized event hub.

From the documentation of $dispatch

Dispatch an event, first triggering it on the instance itself, and then propagates upward along the parent chain. The propagation stops when it triggers a parent event listener, unless that listener returns true.

on the other hand $emit:

Trigger an event on the current instance. Any additional arguments will be passed into the listener’s callback function.

So you can see, if you are passing communication to multiple layer of parent elements via $dispatch, you have to handle that code differently with $emit

Share:
17,385
Alfred Huang
Author by

Alfred Huang

一切有为法, 如梦幻泡影。 如露亦如电, 应作如是观。

Updated on June 05, 2022

Comments

  • Alfred Huang
    Alfred Huang almost 2 years

    In vue2.0 the event $dispatch and $broadcast is deprecated.

    And I found that $dispatch is similar with $emit.

    What's the differences between them? Is it safe directly replacing $dispatch into $emit when migrating.

  • Alfred Huang
    Alfred Huang over 7 years
    Ok, it means $emit only passes to itself and its parent, while $dispatch passes with bubbling up, is it right?
  • Saurabh
    Saurabh over 7 years
    In context of parent child communication: Yes, However there are other uses of $emit also, which you can explore in documentation. But as you are migrating from vue 1, you need to consider this difference of chain propagation.
  • Mastor
    Mastor about 5 years
    example codepen of a simple Vue element that acts as an eventBus ($on, $emit) codepen.io/intosite/pen/WxQZvq