// event-bus.js import Vue from 'vue' class Bus { // eventName1:[fn1,fn2], // eventName2:[fn3,fn4], this.callbacks = {} $on(name, fn) { this.callbacks[name] = this.callbacks[name] || [] this.callbacks[name].push(fn) } $emit(name, args) { if(this.callbacks[name]) { this.callbacks[name].forEach(cb => { cb(args) }) } } $off(name) { if (this.callbackes[name]){ delete this.callbacks[name] } } } // 注册 function install() { Vue.prototype.$eventBus = new Bus() } export default { install }
挂载
// main.js import Vue from 'vue' import eventBus from './event-bus.js' Vue.use(eventBus)
使用
// 监听 this.$on('event-name', (res) => { console.log(res) // 一系列的操作.. }) // 触发 eventBus() { this.$eventBus.$emit('event-name', '我是bus传递过来的消息') }