1、定义一个ts文件(可封装成公用的)
type BusEvent = {
emit: (name) => void
on: (name, callback) => void
}
type PramsType = string | number | symbol
type List = {
[key:PramsType ]: Array<Function>
}
class Bus implements BusEvent {
list: List
constructor (){
this.list = {}
}
emit (name:string,...args:Array<any>){
let busName:Array<Function> = this.list[name]
busName.forEach(fn =>{
fn.apply(this, args)
})
}
on (name:string, callback:Function){
let fn:Array<Function> = this.list[name] || []
fn.push(callback)
this.list[name] = fn
}
off (name: string) {
if (this.list[name]) {
delete this.list[name];
}
}
}
export default new Bus()
2、兄弟 A 发送消息:
import BusEvent from './busEvent'
BusEvent.emit('自定义事件名称',flag)
3、兄弟 B 接收消息:
import BusEvent from './busEvent'
BusEvent.on('自定义事件名称',(flag) =>{
console.log(flag)
})
4、在组件销毁前,清除自定义事件,不然会操作多次
BusEvent.off('自定义事件名称')