1.初始化 vue時,會通過數據劫持 給data中的每個屬性設置get和set方法2.每個get中通過dep.depend()將當前的watch添加到subs搜集器中3.設置新值時,觸發set中的dep.notify()去通知 watch.update更新 視圖現在疑問1.data中的每個屬性觸發set,怎么知道當前屬性跟哪個 dep對應綁定的呢?我看網上說是通過閉包,這樣的話,data中變量過多,會不會產生性能問題2.初始化vue實例時,Dep.taget的當前watch,是什么時候入棧的,我看watch里的get方法頂部pushTarget入棧,后方法結束前又popTarget了### 問題描述
2 回答

飲歌長嘯
TA貢獻1951條經驗 獲得超3個贊
可以再網上找一些簡單的實現:
function observer(obj) { if (!obj || typeof obj !== 'object') { return ; } Object.keys(obj).forEach((key) => { reactive(obj, key, obj[key]); }); }function reactive(obj, key, value) { observer(value); const dep = new Dep(); Object.defineProperty(obj, key, { configurable: false, enumerable: true, get() { Dep.target && dep.addSub(Dep.target); return value; }, set(newValue) { value = newValue; dep.notify(); } }) }class Dep{ constructor() { this.subs = []; } addSub(sub) { this.subs.push(sub); } notify() { this.subs.forEach(sub => { sub.update(); }); } }class Watcher{ constructor(vm, exp, cb){ this.vm = vm; this.exp = exp; this.cb = cb; this.value = this.get(); } get() { Dep.target = this; const value = this.vm[this.exp]; Dep.target = null; return value; } update() { const oldValue = this.value; const value = this.get(); if (oldValue !== value){ this.value = value; this.cb.call(this.vm, value, oldValue); } } }
添加回答
舉報
0/150
提交
取消