Sometimes, we want to make any 2 components communicate with each other in our Vue.js app.
In this article, we’ll look at how to make any 2 components communicate with each other in our Vue.js app.
Communication Across Any Components
We can communicate between any components with the this.$dispatch
method to dispatch an event that’s propagated to all components.
Then we can use this.$on
to listen to the event that’s dispatched by this.$dispatch
.
For example, we can write the following in one component:
export default {
...
created() {
this.$dispatch('child-created', this)
}
...
}
Then in another component, we can write:
export default {
...
created() {
this.$on('child-created', (child) => {
console.log(child)
})
}
...
}
We emit the event in the created
hook so the event is emitted when the component is created but DOM content isn’t loaded yet.
In the 2nd component, we add the event listener in the created
hook so that we can listen to events as soon as the component code is loaded.
child-created
is the event name.
The child
parameter has the event data in the 2nd argument of $dispatch
.
Conclusion
We can communicate between any components with the this.$dispatch
method to dispatch an event that’s propagated to all components.
Then we can use this.$on
to listen to the event that’s dispatched by this.$dispatch
.