当前位置: 首页 > Web前端 > vue.js

vuewatch源码分析

时间:2023-03-31 18:35:25 vue.js

每个watch属性创建一个观察者(Watcher实例),根据属性名(如person.name)生成获取属性值的方法保存在观察者的getter变量中,属性值改变后调用的函数也会保存在观察者的cb变量上。观察者初始化时,调用getter函数读取watch监听的数据(响应数据),通过data属性定义的get将观察者添加到值的依赖收集器中。varWatcher=functionWatcher(vm,expOrFn,cb,options,isRenderWatcher){this.vm=vm;...这个.cb=cb;...if(typeofexpOrFn==='function'){this.getter=expOrFn;}else{this.getter=parsePath(expOrFn);//根据属性名生成获取属性值的方法...}this.value=this.lazy?undefined:this.get();};//解析属性名functionparsePath(path){if(bailRE.test(path)){return}varsegments=path.split('.');返回函数(obj){for(vari=0;iindex&&queue[i].id>watcher.id){//在当前处理的wacher后面插入,id只需要比之前的id大即可i--;}queue.splice(i+1,0,观察者);//根据id的大小插入到未处理的watch中}//flush入队if(!waiting){waiting=true;if(process.env.NODE_ENV!=='production'&&!config.async){flushSchedulerQueue();返回}nextTick(流感shSchedulerQueue);}}}