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.
$emit to emit a custom event. Let's take a look at an example where we have MyTextInput. vue that contains a label and a text input. Whenever the text changes, we want to emit an event with the uppercased value of our input. Instead of calling $emit from our template, we can call a component method instead.
Dispatch triggers an action whereas commit triggers a mutation. $dispatch is always used from your methods in routes/components. It sends a message to Vuex store to perform some action. The action can be performed any time after the current tick so that it will not affect the frontend performance.
prevent is a modifier for v-on:click . Another handy modifier is . self , which tells Vue to only evaluate v-on:click if the element itself is clicked, as opposed to one of its children. For example, Vue only calls the below v-on:click handler when you click on the outer div , not the inner div .08-Jul-2020.
mapActions is just a helper that lets you call those methods from within a Vue component.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With