To send an event: vm.$emit('new-message');
To catch an event: vm.$on('new-message');
To send an event to all components down: vm.$broadcast('new-message');
To send an event to all components up: vm.$dispatch('new-message');
Note: $broadcast and $dispatch are deprecated in Vue2
When should I use events ?
The following picture illustrates how component communication should work. The picture comes from The Progressive Framework slides of Evan You (Developer of VueJS).
Here is an example of how it works :
The example above can be improved !The example above shows how the component communication works. But in case of a custom
input component, to synchronize the parent variable with the value typed, we sould use
In Vue1, you should use .sync on the prop sent to the
In Vue2, there is a special 'input' event you can $emit. Using this event allows you to put a vmodel directly on the
JS Vue 1 & 2
Notice how faster the input is updated.
How to deal with deprecation of $dispatch and $broadcast? (bus event pattern)
You might have realized that $emit is scoped to the component that is emitting the event. That's a problem when you want to communicate between components far from one another in the component tree.
Note: In Vue1 you coud use $dispatch or $broadcast, but not in Vue2. The reason being that it doesn't scale well. There is a popular bus pattern to manage this:
You just need to understand that any Vue() instance can $emit and catch ($on) an event. We just declare a global Vue instance call bus and then any component with this variable can emit and catch events from it. Just make sure the component has access to the bus variable.