vue中使用eventBus
EventBus是消息传递的一种方式,基于一个消息中心,订阅和发布消息的模式,称为发布订阅者模式。
1.新建 eventBus.js
import Vue from 'vue';
let bus = new Vue();
Vue.prototype.$eventBus = bus;
export default bus;
2.在两个vue组件中引入 eventBus.js
//eventBus.js为自己项目中对应的路径
import bus from '../utils/eventBus.js'
3.使用
//要发送数据的test1.vue中发送事件
bus.$emit('show', "this is a msg");
//要接收数据的test2.vue中发送事件
bus.$on('show', msg => {
//接收的信息
console.log(msg);
})