The event bus / publish-subscribe pattern, despite the bad press it sometimes gets, is still an excellent way of getting unrelated sections of your application to talk to each other. But wait! Before you go waste your time on another library, why not use Vue’s powerful built-in event bus?
Creating the event bus
The first thing you’ll need to do is create the event bus and make the bus available to each Vue instance by defining them on the prototype.
| |
In your Vue component where you want to receive on the $bus put the following code. This listens to incoming requests send over the event bus.
| |
To trigger the defined event you simply use the following on any of your Vue components.
| |
Use case
In the following example, I trigger the visibility of a button located next to my breadcrumbs. Depending on what page is shown I want to manipulate the button text and function it triggers.
| |
Now you can trigger the button’s visibility and action from any of your Vue components.
| |
In more complex cases, you should consider employing a dedicated state-management pattern. Full documentation