标签:视图 vue.js func getter === tar 构造 收集 更新
Object.defineProperty(obj, prop, descriptor)
function defineReacive(obj, key, val){
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() {
return val;
},
set(newVal) {
if(val === newVal) return;
val = newVal;
callback(newVal);
}
})
}
function observer(val){
if(!val || typeof val !== 'object') return;
Obejct.keys(val).forEach(key => {
defineReactive(val, key, val(key));
})
}
class MockVue {
constructor(options) {
this._data = opations.data;
observer(this._data);
}
}
let v1 = new MockVue({
data: { }
})
class Dep {
constructor() {
this.subs = [];
}
addSub(sub) {
this.subs.push(sub);
}
notify() {
this.subs.forEach(sub => {
sub.update();
})
}
}
class Watcher {
constructor() {
Dep.target = this;
}
update() {
console.log('update...');
}
}
function defineReacive(obj, key, val){
+ const dep = new Dep();
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get() {
+ dep.addSub(Dep.target);
return val;
},
set(newVal) {
if(val === newVal) return;
val = newVal;
- callback(newVal);
+ dep.notify();
}
})
}
class MockVue {
constructor(options) {
this._data = options.data;
observer(this._data);
new Watcher(); // Dep.target会指向这个watcher对象
console.log('触发getter');
}
}
标签:视图 vue.js func getter === tar 构造 收集 更新
原文地址:https://www.cnblogs.com/colima/p/10508913.html