預知詳情可點這裏,看這位大佬的this
建立一個Bus類負責事件派發.監聽和回調管理spa
class Bus { constructor () { // { // 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)) } } } // main.js Vue.prototype.$bus = new Bus() // child1 this.$bus.$on('foo', handle) // child2 this.$bus.$emit('foo')