实现vue事件总线,巨简单

1,248 阅读1分钟
//此篇记录小知识点,用于后期回顾,如有问题,请大佬指出

首先介绍下使用步骤

  1. Vue.prototype.bus = new Vue()

  2. this.bus.$on(注册事件名,回调函数)

  3. this.bus.$emit(触发事件,传入参数)

//以上可以看出vue构造函数的原型对象上有on emit方法
    
//下面是实现过程
class MyVue{
        constructor(){
            //用于储存注册的事件
            this.eventCollection = {}
        }
        //注册事件
        on(event,fn){
            //可以多个地方都注册同一个事件,届时需要挨个通知
            //无则创建事件集合(数组)
            if(!this.eventCollection[event]){
                this.eventCollection[event] = []
            }
            this.eventCollection[event].push(fn)
        }
        //如果注册过这个事件,则遍历执行回调
        emit(event,...params){
            if(this.eventCollection[event]){
                this.eventCollection[event].forEach(fn => {
                    fn(...params)
                })
            }
        }
        //删除指定事件的,指定回调函数
        off(event,fn){
            var callbacks = this.eventCollection[event]
            if(callbacks){
                var index = callbacks.indexOf(fn)
                //注意splice方法负数就是(arr.length + 负数)位置向后删除的
                if(index !== -1){
                    callbacks.splice(index,1)
                }
            }
        }
    }