模拟Vue中的组件通信($on,$emit)
class MyEvent { protected readonly store: { [key: string]: Function }; private static instance: MyEvent; constructor() { if (!MyEvent.instance) { this.store = {} MyEvent.instance = this } return MyEvent.instance } $on(type: string, callBack: Function) { if (!this.store[type]) { this.store[type] = callBack } } $emit(type: string, data?: any) { if (!this.store[type]) { console.warn(`当前${type}没有被注册!`) } else { let fn = this.store[type] fn(data) } } $off(type: string) { delete this.store[type] }}let eve = new MyEvent()eve.$on("success",function(e){ console.log(e)})eve.$emit("success",{detail:"ok"})