vue2 响应式原理是建立在javascript订阅者模式和Object.defineProperty()的基础之上实现的,下边用代码模拟一下vue2的响应式原理的核心部分 (vue3响应式原理使用es6的proxy实现)
let data = { price: 5, quantity: 2 };
let observer = null,
total = 0;
//观察者模式 [或发布者订阅模式]
class Subject {
constructor() {
this.observers = [];
}
addObserver() {
if (observer && !this.observers.includes(observer)) {
this.observers.push(observer);
}
}
notify() {
this.observers.forEach((observer) => {
observer();
});
}
}
Object.keys(data).forEach((key) => {
let interval = data[key];
const subject = new Subject();
Object.defineProperty(data, key, {
get() {
subject.addObserver();
return interval;
},
set(newVal) {
interval = newVal;
//通知watcher
subject.notify();
}
});
});
function watcher(fn) {
observer = fn;
observer();
}
//每个data实例都对应一个watcher
watcher(() => {
total = data.price * data.quantity;
});
本文由 dealdot <dealdot#163.com> 创作, Full Stack Developer @ DeepBlue
本文最后编辑时间为: Aug 19, 2021 at 16:37 pm
转载请注明来源