VueJs Event Bus Example

  • 03-06-2022
  • 663
  • Vue
  • Haresh Chauhan

What is bus?

The event bus is a special vue instance that will allow the data to pass from one component to another component. It will emit the data in one component and listen to another component, without helping of props or parent component.

It is a central communication event in the whole project, this event works as a central communication, Which will exchange data among all components in the vue project.

In another word we can say vue bus Event nothing but a global instance that will pass the data from one component to any component of the project without the helping of props and parent component.

It is made use of $on, $emit, $off the property of the vue object that emits out events and passes data on it.

As it is worked center communication just needs to emit one time and make it use whole project components at a timed event will work.

The bus is one type of global variable that will help us to run global project events or pass data among whole project components.

So in this post, we will learn how to use Bus in vue js with an example.

src/main.js

The first step is to define the bus event in main.js and export it to the project.

export const bus = new Vue(); this will define your bus event globally in main file.

After defining the bus variable we have to make use Vue.use(bus) using this term.

import Vue from 'vue'
import App from './App.vue'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import axios from 'axios'
import VueAxios from 'vue-axios'

import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'


export const bus = new Vue(); // define bus and export

Vue.use(VueAxios, axios);
Vue.use(BootstrapVue);
Vue.use(IconsPlugin);
Vue.use(bus); // use bus here

Vue.config.productionTip = false

new Vue({
    el: '#app',
    render: h => h(App),
})

src/App.vue

App.vue This is my root component I am imported all these three-component in side this component.

HeaderComponent, ContentComponent, and FooterComponent will provide a basic web design structure just for understanding purposes.

<template>
  <div id="app">
      <header-component></header-component>
      <content-component></content-component>
      <footer-component></footer-component>
  </div>
</template>

<script>

import HeaderComponent from './components/HeaderComponent.vue'
import ContentComponent from './components/ContentComponent'
import FooterComponent from './components/FooterComponent'

export default {
  name: 'App',
  components: {
    HeaderComponent,
    ContentComponent,
    FooterComponent
  }
}
</script>

<style scoped>

</style>

src/components/HeaderComponent.vue

Header component I just add simple title text, But what I want whenever I click on my header component on that time method will emit something data.

So when I click on the header component changeTitle methods will change the title to Webappfix.com, Then it will emit an event to the bus with the name titleChange.

<template>
  <div class="container-fluid text-center text-white py-4" style="background:green" @click="changeTitle">
    <h3>{{ title }}</h3>
  </div>
</template>

<script>

import {bus} from '../main' // bus import from main file which already define in main.js

export default {
    name:'HeaderComponent',

    data(){
        return{
            title:'This is Title',
        }
    },

    methods:{

        changeTitle(){

            this.title = 'Webappfix.com';

            bus.$emit('titleChange',this.title);
        }
    }

}
</script>

src/components/FooterComponent.vue

After emitting a bus event from HeaderComponent that event name I called in FooterComponent inside created method and given that event name titleChange it will pass the data from the HeaderComponent and append to copyright variable and it will change itself when we will click on the header.

<template>
  <div class="container-fluid text-center text-white py-5" style="background:#00ab41">
    <h2>Copyright @ 2022 | {{ copyright }}</h2>
  </div>
</template>

<script>

import { bus } from '../main' // bus import from main.js

export default {
    name:'FooterComponent',
    
    data(){
        return{
            copyright:'This is Title'
        }
    },

    created(){
      
        bus.$on('titleChange',(data) => {

            this.copyright = data
        })
    }
}
</script>

src/components/ContentComponent.vue

This simple content component will help use between header and footer just for clear understanding.

<template>
  <div class="container">
      <br>

      <div class="row">
          <div class="col-4">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Incidunt assumenda consectetur libero enim fuga expedita hic laborum earum, saepe placeat totam aliquid similique maxime molestiae! Atque ab quaerat iste unde.</div>
          <div class="col-4">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Incidunt assumenda consectetur libero enim fuga expedita hic laborum earum, saepe placeat totam aliquid similique maxime molestiae! Atque ab quaerat iste unde.</div>
          <div class="col-4">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Incidunt assumenda consectetur libero enim fuga expedita hic laborum earum, saepe placeat totam aliquid similique maxime molestiae! Atque ab quaerat iste unde.</div>
      </div>
      <br>

      <div class="row">
          <div class="col-4">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Incidunt assumenda consectetur libero enim fuga expedita hic laborum earum, saepe placeat totam aliquid similique maxime molestiae! Atque ab quaerat iste unde.</div>
          <div class="col-4">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Incidunt assumenda consectetur libero enim fuga expedita hic laborum earum, saepe placeat totam aliquid similique maxime molestiae! Atque ab quaerat iste unde.</div>
          <div class="col-4">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Incidunt assumenda consectetur libero enim fuga expedita hic laborum earum, saepe placeat totam aliquid similique maxime molestiae! Atque ab quaerat iste unde.</div>
      </div>
    <br>
    
  </div>
</template>

<script>
export default {
  name:'ContentComponent',
}
</script>

When your project runs it will show the title and footer title like the below image given.

After clicking on the header changeTitle the method sends an event to bus with the name of the event changeTitle. After sending an event to bus I called this bus Event in FooterComponent . So as it send changeTitle event from HeaderComponent it will also affect FooterComponent and change the header title and offer title when I clicked on the header.

Example Output :

gif

On refresh page that default, But as I clicked on header both header and footer title changed together using bus event.

Thanks for reading our post.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :