Building a Simple EventBus in Vue.js
Whenever an Vue.js application outgrows a certain simplicity, you isolate components to keep complexity under control. That makes them reusable, testable and maintainable. However, isolation makes it harder for components to communicate with each other. Where before there were parent and child components, the data flow is now interrupted. Another way has to be found for cross-component communication.Event-based Communication
If passing props is not an option, the most commonly used way of exchanging information among components is to use Events. Vue.js already uses Events frequently, but mostly between components that are not isolated from each other.All aboard the EventBus
An Event Bus allows communication between components without requiring the components to explicitly register with one another. They don’t even need to be aware of their existence. The Event Bus is the central instance for all Events, and every component can publish or subscribe to it. This way, all components can talk to each other no matter what their relationship to each other is.
Vue.js already ships with everything you need to build your own Event Bus. Every Vue.js instance is able to emit and receive Events, since these functions are used to communicate between linked components. They also work for isolated components, with a very small change.
For the Event Bus, just use an empty Vue.js instance.
And that’s it. Every component can now use that Vue.js instance to send or listen to Events.
Both components use the globally available Event Bus to communicate. With actual components being used, it looks like this:
Event Bus with 4 components reacting to each otherTips andTricks
In a larger Vue.js project, you would likely abstract the Event Bus into a single file, importing it into every component file where it needs to be used. This way, it does not pollute the global namespace.
The empty Event Bus instance does not need to stay empty. You can enrich the instance itself with logic to turn it into a service, maybe communicating with a real-time backend through websockets and passing new server-side events to the components via client-side events. Since your events are now handled at a central location, these things just got a lot easier.