Khi 2 component cùng cha, có thể send data cho nhau bằng cách thông qua component cha
Tuy nhiên, với 2 component khác xa nhau. Có thể dùng 1 đối tượng Vue để tạo sự kiện qua nó
1. Tại file ./src/main.js
1 2 3 4 5 6 7 8 9 10 |
import Vue from 'vue' import App from './App.vue' //Tạo 1 instance như 1 đối tượng vận chuyển data, cần gọi trước #app (ở dưới), export const eventBus = new Vue(); new Vue({ el: '#app', render: h => h(App) }) |
2. Tại Component thứ 1 gửi data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
//Tạo button để bắt đầu sự kiện "sendOtherChild" <template> <div> <input type="text" v-model="child_send" /><br /> <button @click="sendOtherChild">Send To Other Children</button> <p>Child-1 Send: {{ child_send }}</p> </div> </template> <script> //Lấy đối tượng "eventBus" import { eventBus } from "../../main.js"; export default { //Giả sử data gửi đi là biến: "child_send" data: function() { return { child_send: "xyz" }; }, methods: { //Dùng "$emit" của "eventBus" để gửi sự kiện đi //"takeOtherChild": tên sự kiện //"this.child_send": data gửi đi sendOtherChild() { eventBus.$emit("takeOtherChild", this.child_send); } }, }; </script> <style scoped></style> |
2. Tại Component thứ 2 nhận data
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<template> <div> <p>Other Child Receive: {{ other_child_reveive }}</p> </div> </template> <script> //Lấy đối tượng "eventBus" import { eventBus } from "../../main.js"; export default { //Giả sử data nhận về sẽ cập nhật vào biến "other_child_reveive"; data: function() { return { other_child_reveive: "0" }; }, //Cần cho phép đối tượng eventBus được thực hiện lắng nghe sự kiện ngay khi Component khởi tạo //Nếu để vào methods chẳng hạn, thì phải đợi methods run rồi mới bắt đầu lắng nghe //Như vậy trước khi methods run, nếu có sự kiện xảy ra rồi thì sẽ không lắng nghe được //Vì vậy cần để ở "created" luôn created() { eventBus.$on("takeOtherChild", data => { this.other_child_reveive = data; }); } }; </script> <style scoped></style> |