刚写的原理,先放上来再说,后续补充解说
wather.js
//观察者的目的就是给需要变化的那个元素增加一个观察者,当数据变化后,执行对应的方法。
//vue的watch方法也是靠这个
//用新值和老值进行比较,如果发生变化,就调用更新方法
//vm.$data expr
class Watcher{
constructor(vm,expr,cb){//cb就是更新方法
this.vm = vm;
this.expr = expr;
this.cb = cb;
//先获取一下老值
this.value = this.get();
}
getVal(expr,vm){//获取实例上对应的数据
//reduce
expr = expr.split('.');//[message,a,b,c]
return expr.reduce((prev,next) => {//vm.$data.message
return prev[next];
},vm.$data)
}
getTextVal(expr,vm){
return expr.replace(/\{\{([^}]+)\}\}/g,(...a) => {
return this.getVal(a[1],vm);
})
}
//获取老值
get(){
Dep.target = this;
//每次执行getVal的时候,会调对象的get方法,也就是observer中的get方法
let oldValue = this.getVal(this.expr,this.vm);
Dep.target = null;
return oldValue;
}
//对外暴露的方法,老值与新值进行比较,如果不一样,就执行下cb
update(){
let newValue = this.getVal(this.expr,this.vm);
let oldValue = this.value;
if(newValue != oldValue){
this.cb(newValue);//调用watch的callback
}
}
}
//用新值和老值进行比较,如果发生变化,就调用更新方法
//vm.$data expr