You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
$emit(event){letcbs=this._events[event];if(cbs){constargs=[].slice.call(arguments,1);//将类数组转换成数组,并取除第一个参数以外的所有参数for(leti=0,l=cbs.length;i<l;i++){try{cbs[i].apply(this,args);}catch(e){handleError(e,this,`event handler for "${event}"`);}}}returnthis;}
The text was updated successfully, but these errors were encountered:
Vue事件机制本质上是一个发布-订阅模式的实现。在注册事件时,将回调函数收集起来,在触发事件时将收集起来的事件依次调用即可。
在执行new Vue时,Vue会执行this._init方法进行一系列初始化操作,其中会在vue实例上创建一个_events属性,用来存储事件。
$on
实例方法的原理:如果event是数组,则递归对每一项调用$on,使回调可以被注册到数组中每项事件名所指定的事件列表中。当不是数组时,就向对应的事件列表中注册回调。
$off
实例方法的原理:用法:移除自定义的事件监听器
$once
实例方法实现原理:监听一个方法,但只触发一次。所以实现思路是:在$once中调用$on来监听自定义事件,当事件触发后会执行拦截器,将监听器从事件列表中移除。
$emit
实例方法实现原理:触发当前实例上的事件,实现思路是:使用事件名从vm._events中取出对应的事件监听器回调函数列表,然后依次执行列表中的监听器回调并将参数传递给监听器回调。
The text was updated successfully, but these errors were encountered: