DEV Community

Cover image for Event bus in Vue 3
Reda-Hammada
Reda-Hammada

Posted on

Event bus in Vue 3

Introduction :

Vue.js provides an efficient seamless way to communicate with sibling components using emit, but sometimes we want to trigger a method and pass data to it from a sibling component, this scenario sounds familiar, right?

No worries a global event bus comes to the rescue, which is what we would usually use to trigger a method from a sibling component, but that got deprecated in Vue 3.

in Vue 2 it would be something like that

export const bus = new Vue();

bus.$on(...)

bus.$emit(...)

Enter fullscreen mode Exit fullscreen mode

In Vue 3 we would need to install an external library called Mitt

npm install --save mitt

Scenario :

now let's picture a scenario, where we have component A and component B, they are both sibling components, component A has a button, which if clicked will invoke a method in component B, let see how this works.

in main.js

We have registered the mitt globally we will inject it in both components to trigger the method by injecting it

import { createApp } from "vue";
import mitt from 'mitt';

const app = createApp(App);

const eventBus = mitt();

// we need to provide it to the app to be used globally
app.provide('eventBus',eventBus);
Enter fullscreen mode Exit fullscreen mode

in Component A:

component A will emit the event when the button is clicked, which will result in passing a param to component B once mounted

<script>

export default {
  name: "AppSideNav",
  // we inject the event bus in the component
  inject: ["eventBus"],
  data() {
    return {

    };
  },
  methods:{
    triggerMethod(param){
        this.eventBus.emit("trigger-method-in-componentB", param);

    }
  }

}
</script>
<template>
  <div> 
    <button @click='triggerMethod(param)' >
       click me !
     </button>
   </div>
</template>
Enter fullscreen mode Exit fullscreen mode

in Component B:

we subscribe to the emitted event that will trigger the method sayMessage() in component B to be invoked.


<script>
export default {
  name: "AppBoard",
    // we inject the eventbus in the component B

  inject: ["eventBus"],

  data(){
    return{
      message:'',
    },

  },
   methods:{
       sayMessage(){
          console.log(this.message)
       }
    },
   mounted() {
    this.eventBus.on("trigger-method-in-componentB", (param) => {
      this.message = param;
      this.sayMessage();

    });

  },
 </script>

Enter fullscreen mode Exit fullscreen mode

Thank you for reading!

Top comments (1)

Collapse
 
alecita profile image
Alejandra

Thank youuuuuuuuuuu!!!!!!! <333