Vuejs EventBus – Send Data Between Components
In this tutorial, you learn how to share data between components using EventBus in Vuejs.
It’s just a publish – subscribe pattern.
What that means is… we can publish a piece of data from one component and make it available to any other components to subscribe into to receive data.
When you publish data using $Eventbus, it becomes global so it can be accessible in any part of the application.
Create An EventBus Object
Create a new file called EventBus.js inside the src directory
import Vue from 'vue';
export const EventBus = new Vue();
Send Data Using $emit Event
Import EventBus in the component that you want to send data from.
import {EventBus} from “@/EventBus”;
Send Data Using $emit event wherever makes sense depends on your application.
EventBus.$emit("name", "Raja Tamil");
The $emit() method takes two arguments…
1. Custom event name in this case name and
2. The actual data that we want to send…in this case Raja Tamil.
Receive Data Using $on Event
Import EventBus in the component that you want to receive data to.
import {EventBus} from “@/EventBus”;
Receive Data Using $on event inside mounted() function
EventBus.$on("name", data => {
console.log(data); // Raja Tamil
})