/*
事件池
eventList = {
handle:[fn1,fn2,fn3]
abc:[fn1,fn2,fn3]
}
||
eventList = {
}
$on(eventName,callback)
判断当前事件名称是否存在,如果不存在则创建一个key值为事件名称 value为一个数组
将callback push到数组中
如果事件名称存在则直接添加到数组中去
$emit(eventName,[params])
判断当前事件名称是否存在,如果存在则遍历数组,得到所有的函数,并执行。然后将params当做实参传递到函数中去
$off(eventName,[callback])
判断当前事件名称是否存在,如果存在继续判断第二个参数是否存在,如果存在则找到相对于的下标 然后将函数在数组中移除
如果不存在则将整个数组清空
*/
const eventList = {}
const $on = (eventName,callback)=>{
if(!eventList[eventName]){
eventList[eventName] = [];
}
eventList[eventName].push(callback)
}
const $emit = (eventName,params)=>{
if(eventList[eventName]){
let arr = eventList[eventName];
arr.map((cb)=>{
cb(params);
})
}
}
const $off = (eventName,callback)=>{
if(eventList[even
Vue-封装-$on $emit $off(封装事件订阅)
最新推荐文章于 2024-07-04 10:41:11 发布
本文详细介绍了如何在Vue应用中封装和使用$on、$emit和$off事件管理方法,提升组件间的通信效率。通过自定义事件中心,实现事件订阅、发布和取消订阅,帮助开发者更好地控制组件间的交互和状态管理。
摘要由CSDN通过智能技术生成