Skip to content
字数
159 字
阅读时间
1 分钟

evnet-bus 我们常用于没有关系的组件间的通信,挂载在 Vue. prototype 之上

js
// 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
}

挂载

js
// main.js

import Vue from 'vue'
import eventBus from './event-bus.js'
Vue.use(eventBus)

使用

js
// 监听
this.$on('event-name', (res) => {
    console.log(res)
    // 一系列的操作..
})

// 触发
eventBus() {
	this.$eventBus.$emit('event-name', '我是bus传递过来的消息')
}

本质上就是一个发布订阅模式

贡献者

The avatar of contributor named as jiechen jiechen

页面历史

撰写