平常工作中经常会用到event-bus来进行组件通信,但对其实现原理却没有深究过,偶然间看到大圣老师的一篇博客,让人获益匪浅,原来如此简单
evnet-bus我们常用于没有关系的组件间的通信,挂载在Vue.prototype之上,下面直接上代码
// 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传递过来的消息')
}
这样我们就手动实现了简单的event-bus,当然我们最常用的方法是新建一个空的Vue实例
Vue.prototype.$bus = new Vue()
大家看看就当娱乐就好,大佬们勿喷