vue3使用eventBus需要自己定义一个ts文件来模拟事件车,先创建一个ts文件
class eventBus {list: { [key: string]: Array<Function> };constructor() {// 收集订阅信息,调度中心this.list = {};}// 订阅$on(name: string, fn: Function) {// this.list[name] = this.list[name] || [];this.list[name] = [];this.list[name].push(fn);// console.log('调用了订阅', this.list, name)}// 发布$emit(name: string, ...args: any[]) {if (this.list[name]) {this.list[name].forEach((fn: Function) => {fn(...args);});}}// 取消订阅$off(name: string) {if (this.list[name]) {delete this.list[name];} else {this.list = {}}// console.log('调用了取消订阅', this.list, name)}
}
export default new eventBus();
在页面中使用:按照自己的文件的位置引入
import eventBus from '@/assets/utils/eventBus'
调用就跟vue2的一样了
created() {eventBus.$on('rwdbSelectChange', this.changeSelect)},beforeUnmount() {eventBus.$off('rwdbSelectChange')},
其实原理和vue2一样都是将事件存入一个叫eventBus的对象使全局都能访问到这个对象的方法