The Wayback Machine - https://web.archive.org/web/20240623140659/https://www.geeksforgeeks.org/pass-data-between-components-using-vue-js-event-bus/
Open In App

Pass data between components using Vue.js Event Bus

Last Updated : 26 Mar, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Component communication in Vue.js can become complicated and messy at times using $emit and props. In real-world applications where the Component tree is nested and big, it is not convenient to pass data using this method as it will only increase the complexity of the application and make debugging very tedious. This is where an event bus comes into the picture.

An Event Bus is nothing but a global Vue instance that is imported by the components involved in communication and passing data. It makes use of the $on, $emit, and $off properties of the Vue object to emit out events and pass on data. An Event Bus provides a very simple and elegant solution to the complex $emit and prop chain which can be very hard to track down while testing and debugging. It acts as a global intermediate for all the components involved to emit out and listen to events and execute methods accordingly.

Syntax:

There is no special syntax for an Event Bus as it is just an instantiation of the Vue class.

const EventBus = new Vue();

Working: 

Consider this simple component tree where we need to share data between the black and the green components. Using $emit and props, this will be a long process of first passing the data and event up through the tree using $emit and then down the tree using props.

However, using an event bus, this can be carried out in a very simple and easy manner.

Example: We will use the same example we have used to illustrate $emit and props here, however, this time using an Event Bus. It is a very basic webpage that displays how many times a button has been clicked. For this, we have 2 components:

  • Component1: Displays the number of times the button in component 2 has been clicked.
  • Component2: A button which when clicked upon increases a counter.

App.js




<template>
<div>
  <Component1></Component1>
  <Component2></Component2>
</div>
</template>
  
<script>
  import Component1 from './components/Component1.vue'
  import Component2 from './components/Component2.vue'
  
  export default {
    name: 'App',
    components: {
      Component1,Component2
    }
  }
</script>


Component1.vue




<template>
  <div class="component1">
    <h1>You have clicked {{ labeltext }} times</h1>
  </div>
</template>
  
<script>
  import EventBus from '../event-bus';
  
  export default {
    name: "Component1",
    data() {
      return {
        labeltext: 0,
      };
    },
    methods: {
      change_n(n) {
        this.labeltext = n;
      },
    },
    created() {
        // Sets up the Event Bus listener using 
        // the custom event name and assosciates
        // it with a component method.
        EventBus.$on("change_n", this.change_n);
      },
    destroyed() {
        // Removes Event Bus listener upon removal
        // of template from DOM.
        EventBus.$off("change_n", this.change_n);
      },
  };
</script>
  
<style scoped>
  .component1 {
    display: block;
    background-color: green;
    height: 15em;
    text-align: center;
    color: white;
    padding-top: 5em;
  }
</style>


Component2.vue




<template>
  <div class="component2">
    <button @click="count">Click</button>
  </div>
</template>
  
<script>
  import EventBus from '../event-bus';
  
  export default {
    name: "Component2",
    data() {
      return {
        nclick : 0,
      };
    },
    methods: {
      count() {
        this.nclick += 1;
        // Emitting a custom-event via the Event Bus
        EventBus.$emit("change_n", this.nclick);
      },
    },
  };
</script>
  
<style scoped>
  .component2 {
    display: block;
    background-color: grey;
    height: 15em;
    text-align: center;
    padding-top: 5em;
  }
</style>


event-bus.js




import Vue from 'vue';
  
// Create a new Vue instance and export it
const EventBus = new Vue();
  
export default EventBus;


Output:



Previous Article
Next Article

Similar Reads

How to pass data into table from a form using React Components ?
React JS is a front-end library used to build UI components. This article will help to learn to pass data into a table from a form using React Components. This will be done using two React components named Table and Form. We will enter data into a form, which will be displayed in the table on 'submit'. Prerequisites:Node JS or NPMReact JSReact Form
3 min read
How to Set URL Query Params in Vue with Vue-Router ?
Vue Router is a navigation library designed specifically for Vue.js applications. In this article, we will learn about the different methods of setting the URL query params in Vue with Vue-Router. Below is the list of all possible methods. Table of Content Using router-linkUsing push() methodUsing replace() methodSteps to Setup the Project Environm
6 min read
Communication between components using $emit and props in Vue.js
Components in Vue.js need to share data with each other sometimes in order to give the desired output. Components in a webpage are in a hierarchical order like a tree. The most basic way of interacting and passing data between components is using $emit and props. $emit and props: In Vue.js, we use $emit to generate custom events for our component.
4 min read
Vue.js Passing Data to Child Components with Props
Vue.js is a progressive javascript framework for developing web user interfaces. It is a performant, approachable, and versatile framework. We can create Single Page Applications as well as Full Stack applications. It is built on top of HTML, CSS, and Javascript which makes it easier for developers to integrate Vue.js in any application at any stag
3 min read
Pass by Value and Pass by Reference in Javascript
JavaScript, being a versatile and dynamic programming language, employs different strategies for passing variables to functions. Two common approaches are "pass by value" and "pass by reference". Understanding these concepts is important for writing efficient and bug-free code. Pass By ValueWhen a function is called, the value of the variable is di
4 min read
Vue.js Transitioning between the Components
Vue.js is a progressive javascript framework for developing web user interfaces. It is a performant, approachable, and versatile framework. We can create Single Page Applications as well as Full Stack applications. It is built on top of HTML, CSS, and Javascript which makes it easier for developers to integrate Vue.js in any application at any stag
3 min read
How to Create Functional Components using Vue Loader ?
Vue.js is a JavaScript framework used in building powerful and beautiful user interfaces. The key feature of Vue.js is its component-based architecture that allows the developers to create reusable and modular components. Functional components, in particular, provide a lightweight and efficient way to build UI elements. In this article, we will lea
3 min read
What is the difference between one-way data flow and two-way data binding in vue.js?
Vue.js is an open-source front-end JavaScript framework for building user interfaces and single-page applications. It follows Model-View-ViewModel (MVVM) architecture pattern. Vue.js has many in-built directives for DOM manipulation such as v-bind, v-on, v-model, etc. In this article, we will learn about the one-way data binding &amp; two-way data
7 min read
Vue.js Custom Directives with Components
Vue.js is a progressive javascript framework for developing web user interfaces. It is a performant, approachable, and versatile framework. We can create Single Page Applications as well as Full Stack applications. It is built on top of HTML, CSS, and Javascript which makes it easier for developers to integrate Vue.js in any application at any stag
3 min read
Vue.js Dynamic Components
Vue.js is a progressive javascript framework for developing web user interfaces. It is a performant, approachable, and versatile framework. We can create Single Page Applications as well as Full Stack applications. It is built on top of HTML, CSS, and Javascript which makes it easier for developers to integrate Vue.js in any application at any stag
3 min read
three90RightbarBannerImg