實(shí)現(xiàn) MVVM 類 Vue 迷你框架(七)
如何實(shí)現(xiàn) MVVM 類 Vue 迷你框架(七)
還有一件事件我們忘記處理,就是對(duì)數(shù)組的處理,Vue 內(nèi)部處理一些數(shù)組方法,例如:push,pop,reverse,shift,unshift,sort,splice
找到原型上的方法 拷貝新的原型 在新的原型上對(duì)這些方法進(jìn)行重寫,這樣就不會(huì)覆蓋原有數(shù)組的原型 通知更新操作
// 數(shù)組響應(yīng)式處理
// push, pop, reverse, shift, sort, splice, unshift
const arrayMethods = ["push", "pop", "reverse", "shift", "unshift", "sort", "splice"];
const originProto = Array.prototype;
const arrayCopyProto = Object.create(originProto);
arrayMethods.forEach(method => {
arrayCopyProto[method] = function () {
// 原始操作
originProto[method].apply(this, arguments);
// 通知更新操作
}
})
我們需要在 Observer 類處理
class Observer {
constructor(value) {
this.$value = value
if (Array.isArray(value)) {
// 處理數(shù)組
// array 覆蓋原型,替換變更操作
value.__proto__ = arrayCopyProto;
// 對(duì)數(shù)組內(nèi)容元素執(zhí)行響應(yīng)式
value.forEach(item => observe(item));
} else {
// 處理對(duì)象
this.walk(value);
}
}
// 遍歷對(duì)象,響應(yīng)式處理
walk(obj) {
Object.keys.forEach(key => defineReactive(obj, key, obj[key]));
}
}
評(píng)論
圖片
表情
