Vue.js what's the difference of $emit and $dispatch?
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
Comments
-
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 over 7 yearsOk, it means
$emit
only passes to itself and its parent, while$dispatch
passes with bubbling up, is it right? -
Saurabh over 7 yearsIn 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 about 5 yearsexample codepen of a simple Vue element that acts as an eventBus ($on, $emit) codepen.io/intosite/pen/WxQZvq