The Vue allows to share data among different components whether it is parent child relation of different levels in DOM tree or sibling components. It can be possible by creating Vue instance at globally and share data using the $emit and $on events. The $emit use to emit data from one component and the emitted data can be received by using $on event but both event should be triggered on same Vue instance.
Share data between different components
1. | Create Vue instance globally |
2. | Import Vue instance and emit data |
3. | Import Vue instance and listen event for the emitted data |
Create Vue instance globally
To create Vue instance globally, it should be define using export keyword, so that it can be accessible in the any Vue application component.
Create Vue instance globally
1 import Vue from "vue";
2 import App from "./App.vue";
3 import router from "./router";
4 import store from "./store";
5 Vue.config.productionTip = false;
6
7
8 export const GlobalEvent = new Vue();
9
10 new Vue({
11 router,
12 store,
13 render: (h) => h(App),
14 }).$mount("#app");
Import Vue instance and emit data
To emit data from the Vue instance, it provides $emit event which takes two argument, the first argument is event name and the second argument is data.
Import Vue instance and emit data
1 <template>
2 <div>
3 <div>Click button to share data between components</div>
4 <button @click="handler">Click</button>
5 </div>
6 </template>
7
8 <script>
9
10 import { GlobalEvent } from "@/main";
11
12 export default {
13 name: "ChildOne",
14 methods: {
15 handler: function () {
16
17 GlobalEvent.$emit(
18 "updateParent",
19 "Message to parent using global event !!"
20 );
21 },
22 },
23 };
24 </script>
25
Import Vue instance and listen event for the emitted data
To listen for the emitted event Vue provide $on event, which takes two arguments, the first argument is event name and the second argument is callback function.
Import Vue instance and listen event for the emitted data
1 <template>
2 <div>
3 <ChildOne />
4 </div>
5 </template>
6
7 <script>
8 import ChildOne from "@/components/ChildOne.vue";
9
10 import { GlobalEvent } from "@/main";
11
12 const data = { name: "Vue Js" };
13 export default {
14 name: "HomeView",
15 data: () => data,
16 components: {
17 ChildOne,
18 },
19
20 mounted: function () {
21
22 GlobalEvent.$on("updateParent", function (data) {
23 console.log(data);
24 });
25 },
26 };
27 </script>
28
Related options for your search