不要认为数据发生改变,界面跟着更新是理所当然的。 Vue 背后做了很多的操作才实现了这个效果
1.Vue 内部是如何监听的呢一个变量 message 数据的发生了改变呢?
答: Object.defineProperty -> 监听对象属性的改变
2.监听到了数据改变,Vue 又如何知道要通知哪些人来让界面发生刷新呢?
既: 页面有三个 {{message}} {{message}} {{message}}, 它怎么知道要通知这三个地方呢?
答: 利用“发布订阅者模式”
Object.defineProperty -> 监听对象属性的改变
const obj = {
message:"11"
}
Object.keys(obj).forEach(key => { //遍历属性
let originalValue = obj[key];
Object.defineProperty(obj, key, {//监听对象属性的改变
set (newValue){
console.log("这里就可以监听到属性" + key + "从" + originalValue + "变成了" + newValue);
//这里就可以告诉用这个值的人,我发生变化了
// 这里就需要获取,我需要告诉谁呢?
originalValue = newValue;
//dep.notify(); 告诉所有之前订阅的人
},
get(){
//给哪些些需要的人,新的值。
//const w1 = new Watcher("Tracy1");
//dep.addSub(w1);
console.log("获取" + key + "的值" + originalValue);
return originalValue;
}
})
})
obj.message = "newName";
发布者订阅者模式
//发布者
function Dep(){
this.subs = [];
this.addSub = function(watcher){
this.subs.push(watcher);
}
this.notify = function(){
this.subs.forEach(item => {
item.update();
})
}
}
//订阅者
function Watcher(name) {
this.name = name;
this.update = function(){
console.log(this.name + "发生改变");
}
}
const dep = new Dep();
const w1 = new Watcher("Tracy1");
dep.addSub(w1);
const w2 = new Watcher("Tracy2");
dep.addSub(w2);
const w3 = new Watcher("Tracy3");
dep.addSub(w3);
dep.notify();
CoderWhy 老师对该模式的步骤分析