1、vue数据的响应式,检测数据的改变
const app = new KVue({
data:{
test:'I am test',
foo:{
bar:"bar"
}
}
});
app.$data.test = "hello";
app.$data.foo.bar = "oh my bar";
class KVue{
constructor(options){
this.$options = options;
//数据响应化
this.$data = options.data;
this.observe(this.$data);
}
observe(value){
if(!value || typeof(value) !== "object"){
return;
}
Object.keys(value).forEach(key => {
this.defineReactive(value,key,value[key]);
})
}
defineReactive(obj,key,val){
this.observe(val); //递归解决数据嵌套
Object.defineProperty(obj,key,{
get(){
return val;
},
set(newVal){
if(newVal === val){
return;
}
val = newVal;
console.log(`${
key}的值更新了 ${
val}`);
}
})
}
}
页面打印效果如下
2、收集数据依赖
发布订阅模式
//Dep:用来管理watcher
class Dep{
constructor(){
//这里存放若干依赖(watcher),一个watcher对应一个属性
this.deps = [];
}
addDep(dep){
this.deps.push(dep);
}
notify(){
this.deps.forEach(v => {
v.update();
})
}
}