当前位置: 首页 > 科技观察

Vue2剥茧-响应式系统改进

时间:2023-03-17 18:30:16 科技观察

本文主要修复了前面代码中的一个问题,废话不多说,下面上代码!从“./reactive”导入场景{观察};importWatcherfrom"./watcher";constdata={text:"hello,world",};observe(data);letshow=true;constupdateComponent=()=>{if(show){console.log(数据.文本);显示=假;}};newWatcher(updateComponent);newWatcher(()=>console.log("Dependency",data.text));data.text="123";首先你可以考虑1分钟,它会输出What。新观察者(updateParentComponent);执行updateParentComponent函数,输出hello,world,text的Dep收集Watcher。newWatcher(()=>console.log("Dependency",data.text));执行匿名函数,输出依赖hello,world,text的Dep收集Watcher。data.text="123";.触发文本集合,依次执行Dep中的Watcher。先执行updateParentComponent。constupdateComponent=()=>{if(show){console.log(data.text);显示=假;}};由于之前执行过一次,所以此时show为false,不会有任何输出。再次执行()=>console.log("Dependency",data.text),输出依赖hello,world。是的,上面是我们所期望的,但实际上输出如下:错误代码dep.js:37:26如下:调用update时,遍历过程中subs[i]变为undefined,导致错误。需要回忆一下我们在Vue2剥茧-响应式系统的分支切换这篇文章中做了什么。如果Watcher中的函数不再依赖于当前属性,我们将当前的Watcher从属性的Dep中移除。移除其实就是调用数组的splice方法直接删除Dep中subs数组的元素。removeSub(sub){remove(this.subs,sub);}导出函数remove(arr,item){if(arr.length){constindex=arr.indexOf(item);如果(索引>-1){返回arr.splice(索引,1);}}}当我们遍历subs数组时:notify(){for(leti=0,l=this.subs.length;i