Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 583
Alfred Huang Avatar asked Dec 02 '16 01:12

Alfred Huang


People also ask

What does $emit do in Vue?

$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.

What is Vue dispatch?

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.

What is click stop Vue?

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.

What is mapActions?

mapActions is just a helper that lets you call those methods from within a Vue component.


1 Answers

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

like image 119
Saurabh Avatar answered Oct 04 '22 04:10

Saurabh