咱們首先來看vue2.x中的實現,爲簡單起見,咱們這裏不考慮多級嵌套,也不考慮數組vue
其本質是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之因此要重新實現,主要有這幾個緣由:ui
Object.defineProperty
的性能開銷。defineReactive
一開始就要對要監聽的對象全部屬性都執行一遍,由於傳統方法要將一個對象轉換成可監聽對象,只能如此。而後咱們來看看一樣的功能採用Proxy會怎樣實現。this
將一個對象轉換成Proxy的方式很簡單,只須要做爲參數傳給proxy便可;spa
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都是nullcode
若是有什麼錯誤請指正,謝謝。server