运用三:
将bus挂载到vue.prototype上(这里用了插件的写法)
// plugin/index.js import Bus from 'vue'; let install = function (Vue) { ... ... // 设置eventBus Vue.prototype.bus = new Bus(); ... ... } export default {install}; // main.js import Vue from 'vue'; import plugin from './plugin/index'; ... ... Vue.use(plugin); ... ...
组件一中定义
... ... mounted () { this.bus.$on('updateData', this.getdata); }
组件二中调用
this.bus.$emit('updateData', {loading: false});
注意:注册的总线事件要在组件销毁时卸载,否则会多次挂载,造成触发一次但多个响应的情况
beforeDestroy () { this.bus.$off('updateData', this.getData); }