<aside> 💡 Note: Event busses have been removed in Vue 3. We are to move to using external libraries for this functionality.
</aside>
First we need to instantiate an event bus. The event bus is just a new Vue instance:
export const myEventBus = new Vue();
Then we need to import the event bus in the components we want to communicate with each other. After that we can send events within components like this:
myEventBus.$emit('myEvent', 'Event Data');
After this in the receiving component use the create hook like the following:
// Within a vue components
export default {
created() {
myEventBus.$on('myEvent', (data) => {
console.log(data); // Outputs: Event Data
});
}
}
You may also consider using the myEventBus.$off() method to unregister event listeners. Using with a method instead of a lambda for a handler makes things easier at that point.