Vue

Global Event Bus Tutorial – Vue.js

Global Event Bus: There is a various way to communicate between Vue component. Props is one of them which is used to communicate from parent component to child component.

But As your application increases in complexity, It becomes a tedious process to pass props down and down and down to child components. So, here we will discuss Event bus.

Here, you can see a live demo on Global Event Bus

You will learn about passing data from parent component to child component using the event bus after completion of the tutorial.

What is EventBus?

Event Bus is easy and quick way to pass data between

Vue.js components

. It is one of the best solutions for small scale to medium scale web application because it can pass data from one component to another component even components are located in the tree structure rather than props.
 

#1: Create a new Vue project

Here, we are using Vue CLI to create a new Vue project so, first of all install Vue CLI globally by the following command

Let’s create a new Vue project by the following command

installing event bus project

#2: Configure Event Bus

To make use of an event bus, we first need to initialize it in main.js like following

Here, We have imported Vue and assigned the instance of Vue to eventBus as globally. Now any component can emit an event and also other components can listen for that event using this event bus.
 

#3: Create a Emit Component

To Emit event data we have created a component which can emit data through event bus.

So, In Above component, We take title and description as input from users and call a submit() method which will emit an event called emitted-data along with a payload data whenever users click the button.
 

#4: Create Listener Component

To listen to emitted data via event bus create a listener component and write the following code.

In Above component, We have created a mounted() method which listens for event called emitted-data using eventBus and show the data which is emitted from parent component.
 

#5: Register Both components

Register both previously created components in App.vue file like

Now, App.vue component is loaded first when we run Vue project so, we have registered those two components in App.vue file.


Finally, We have completed

Event bus demo

in straight forward steps. I hope you have learned from this tutorial. Thank you.
 


About the author

Parth Vakil

Full Stack Developer at Artixun Softwares. My specialty is web development with Laravel/Node development, using JS libraries such as JQuery, Angular, Vue, React and Ionic

Leave a Comment