class Bus {
constructor() {
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')
Vue事件总线的理解
最新推荐文章于 2023-09-04 11:06:48 发布