Create a global Vue.js event bus

Create a global Vue.js event bus

Sometimes when working with a Vue.js application you might require unrelated areas of your application to talk to each other. The standard ‘props down, events up‘ method will not work if your components do not have a direct parent to child relationship. This is when an event bus comes in very useful.

Step 1: Create the event bus

To create the event bus all you need to do is import the Vue library and export an instance of it. This is essentially exporting a component that is completely separate from the rest of your application.

Step 2: Sending an event

To use the event bus you will first need to import it in the components that will send the event.

Below I have an example of a single file component which will send the event. The event bus is imported, and a method executed on a click event which is then emitted via the ‘button-was-clicked’ channel on the event bus.

Step 3: Receiving the event

To receive the event simply import the event bus in your receiving component, and listen for the event on the ‘button-was-clicked’ channel.

If you would like to discuss this article or have any other queries regarding its contents please don’t hesitate to contact me.