Category / Section
How to communicate between Vue Components using Event bus?
1 min read
You can communicate between Vue components by using the Eventbus which can emit an event from one Vue component, and then listen to the emitted event in another component.
This is explained in the following sample code in which, the pageSettings.pageSize property of DataGrid has been updated in the “App” component, when changing the DropDownList value in the “dropdown” Component by using the Event bus.
- First, we need to create an Event bus inside the “main.js” file.
main.js
import Vue from "vue"; import App from "./App.vue"; Vue.config.productionTip = false; export const bus = new Vue(); new Vue({ render: h => h(App) }).$mount("#app");
- Inside the “dropdown” component we have rendered a DropDownList control that has the list of page sizes. Inside the DropDownList change event handler, an event “pageChange” will be emitted using the “$emit” statement with the changed value.
DropDown.Vue
<template> <div class="dd"> <ejs-dropdownlist id="dropdownlist" :dataSource="pageData" :value="value" :change="changeHandler" ></ejs-dropdownlist> </div> </template> <script> import Vue from "vue"; import { DropDownListPlugin } from "@syncfusion/ej2-vue-dropdowns"; import { bus } from "./main"; // Importing the bus from “main.js” Vue.use(DropDownListPlugin); export default Vue.extend({ name: "DropDown", data: function() { return { pageData: [8, 10, 12, 20], value: 12 }; }, methods: { changeHandler: function(args) { bus.$emit("pageChange", args.value); // Event emitting while changing the value } } }); </script>
- The emitted event “pageChange” will be listened by the “$on” statement which is defined inside the ”created” lifecycle hook of Vue Component. Here, we have updated the passed value to the Grid pageSettings.pageSize property.
App.Vue
<template> <div id="app"> <dropdown></dropdown> <ejs-grid ref="grid" :dataSource="data" :allowPaging="true" height="275px"> <e-columns> <e-column field='OrderID' headerText='Order ID' textAlign='Right' width=90></e-column> <e-column field='CustomerID' headerText='Customer ID' width=120></e-column> <e-column field='Freight' headerText='Freight' textAlign='Right' format='C2' width=90></e-column> <e-column field='OrderDate' headerText='Order Date' textAlign='Right' format='yMd' type='date' width=120></e-column> </e-columns> </ejs-grid> </div> </template> <script> import Vue from "vue"; import dropdown from './DropDown.vue'; import { GridPlugin, Page } from "@syncfusion/ej2-vue-grids"; import { bus } from './main'; import { data } from './datasource.js'; Vue.use(GridPlugin); export default { components: { dropdown }, data() { return { data: data }; }, provide: { grid: [Page] }, created (){ // Listen to the emitted event bus.$on('pageChange', (data) => { // Updating the pageSize this.$refs.grid.ej2Instances.pageSettings.pageSize = data; }) } } </script>