EventBus可以使两个组件相互通信。
定义:
// EventBus.js文件
import Vue from 'vue';
export const EventBus = new Vue();
发送事件:
import { EventBus } from './EventBus.js';
EventBus.$emit('eventName', {
text: '需要传递的数据'
});
接收事件:
// 事件监听
import { EventBus } from './EventBus.js';
mounted() {
EventBus.$on('eventName', (msg) =>{
console.log('msg--', msg);
})
}
移除事件:
// $off()事件解绑,可以防止内存泄漏
import { EventBus } from './EventBus.js';
destroyed() {
// 移除指定$on()监听事件
EventBus.$off('eventName');
// 清除所有$on()监听事件
// EventBus.$off();
},