Vue.js —Simple event bus for cross component communication
Vue 2 is pretty strict about communication between components. The standard way to communicate between components is for parents to pass props down to children, and for children to $emit events up to the parent component. You begin to run into issues when you need to emit an event and intercept it several components up a tree or in a sibling component. You’ll find yourself sending the same piece of data up or down the chain or both up and down for sibling components.
In the diagram above, if you wanted to emit an event in Component C and have something react in Component A, you would need to $emit events all the way up the chain to the Root Component, then pass the prop down to Component A from the Root. That’s pretty messy!
The two ways to solve this are by using:
- Global event bus
- Vuex (Not covered in this post)
The Vuex method would involve mutating the piece of data in your data store from Component C and then having component A react to the data in the shared state.
The global event bus method is pretty simple. You instantiate another instance of Vue with nothing in it. Then use that to $emit events and use $on to react to the event.
Here’s an example main.js file where I bound the event bus to the Vue prototype so I can access the bus from within my components via this.$emit() or this.$on()