為什麼Proxy可以優化vue的資料監聽機制
我們首先來看vue2.x中的實現,為簡單起見,我們這裡不考慮多級巢狀,也不考慮陣列
vue2.x中的實現
其本質是new Watcher(data, key, callback)
的方式,而在呼叫之前是先將data中的所有屬性轉化成可監聽的物件, 其主要就是利用Object.defineProperty
,。
class Watcher{ constructor(data, key, cb){ } } //轉換成可監聽物件 function observe(data){ new Observer(data) } //修改資料的getter和setter function defineReactive(obj, key){ let value = obj[key]; Object.defineProperty(obj, key, { enumerable: true, configurable: true, get(){ return value; }, set(newVal){ value = newVal } }) } 複製程式碼
Observer的實現很簡單
class Observer { constructor(data){ this.walk(data); } walk(data){ for(var key in data) { // 這裡不考慮巢狀的問題,否則的話需要遞迴呼叫walk defineReactive(data, key) } } } 複製程式碼
現在怎麼將watcher和getter/setter聯絡起來,vue的方法是新增一個依賴類:Dep
class Watcher{ constructor(data, key, cb){ this.cb = cb; Dep.target = this; //每次新建watcher的時候講給target賦值,對target的管理這裡簡化了vue的實現 data[key];//呼叫getter,執行addSub, 將target傳入對應的dep; vue的實現本質就是如此 } } class Dep { constructor(){ this.subs = []; } addSub(sub){ this.subs.push(sub); } notify(){ this.subs.forEach(sub => sub.cb()) } } function defineReactive(obj, key){ let value = obj[key]; let dep = new Dep(); //每一個屬性都有一個對應的dep,作為閉包儲存 Object.defineProperty(obj, key, { enumerable: true, configurable: true, get(){ dep.addSub(Dep.target) Dep.target = null; return value; }, set(newVal){ value = newVal dep.notify(); } }) } 複製程式碼
以上就是vue的思路,vue3之所以要從新實現,主要有這幾個原因:
Object.defineProperty defineReactive
然後我們來看看同樣的功能採用Proxy會怎樣實現。
Proxy的實現
將一個物件轉換成Proxy的方式很簡單,只需要作為引數傳給proxy即可;
class Watcher { constructor(proxy, key, cb) { this.cb = cb; Dep.target = this; this.value = proxy[key]; } } class Dep { constructor(){ this.subs = [] } addSub(sub){ this.subs.push(sub); } notify(newVal){ this.subs.forEach(sub => { sub.cb(newVal, sub.value); sub.value = newVal; }) } } const observe = (obj) => { const deps = {}; return new Proxy(obj, { get: function (target, key, receiver) { const dep = (deps[key] = deps[key] || new Dep); Dep.target && dep.addSub(Dep.target) Dep.target = null; return Reflect.get(target, key, receiver); }, set: function (target, key, value, receiver) { const dep = (deps[key] = deps[key] || new Dep); Promise.resolve().then(() => { dep.notify(value); }) return Reflect.set(target, key, value, receiver); } }); } var state = observe({x:0}) new Watcher(state, 'x', function(n, o){ console.log(n, o) }); new Watcher(state, 'y', function(n, o){ console.log(n, o) }); state.x = 3; state.y = 3; 複製程式碼
也許一開始我們只關心x
和y
,那麼就不會對其他的屬性做相應的處理,除非新增watcher,其他時間target都是null
如果有什麼錯誤請指正,謝謝。