前言
最近在嘗試用Vue.js重構公司的現有業務代碼,組件化的設計思路和MVVM的思想讓我深深沉迷於其中。但是是踩到了不少坑,就比如這篇文章介紹的數組綁定後的更新檢測。
相信大家都知道Observer,Watcher,vm 可謂 Vue 中比較重要的部分,檢測數據變動後視圖更新的重要環節。在 vue.js中$watch的用法示例 中,我們討論了如何實現基本的 watch 。
接下來,我們來看看如何實現數組變動檢測。
例子:
// 創建 vm
let vm = new Vue({
data: {
a: [{}, {}, {}]
}
})
// 鍵路徑
vm.$watch('a', function () {
// 做點什麼
})
思路
在 js 中, 很容易實現 hook, 比如:
// hook 一個 console。log
let _log = console.log
console.log = function (data) {
// do someting
_log.call(this, data)
}
我們只要實現自定義的函數,就能觀測到數組變動。
Vue.js 中使用Object.create() 這個函數來實現繼承, 從而實現自定義函數,以觀測數組。
// 簡單介紹 var a = new Object(); // 創建一個對象,沒有父類 var b = Object.create(a.prototype); // b 繼承了a的原型
繼承
array.js定義如下:
// 獲取原型
const arrayProto = Array.prototype
// 創建新原型對象
export const arrayMethods = Object.create(arrayProto)
// 給新原型實現這些函數
[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// 獲取新原型函數 (此時未實現 undefined)
const original = arrayProto[method]
// 給新原型添加函數實現
Object.defineProperty(arrayMethods, method, {
value: function mutator() {
let i = arguments.length
// 獲取參數
const args = new Array(i)
while (i--) {
args[i] = arguments[i]
}
// 實現函數
const result = original.apply(this, args)
// 獲取觀察者
const ob = this.__ob__
// 是否更改數組本身
let inserted
switch (method) {
case 'push':
inserted = args
break
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
// 觀察新數組
inserted && ob.observeArray(inserted)
// 觸發更新
ob.dep.notify()
return result
},
enumerable: true,
writable: true,
configurable: true
})
})
ok, 我們定義完了 array.js, 並作為模塊導出,修改 Observer 的實現:
export function Observer (value) {
this.dep = new Dep()
this.value = value
// 如果是數組就更改其原型指向
if (Array.isArray(value)) {
value.__proto__ = arrayMethods
this.observeArray(value)
} else {
this.walk(value)
}
}
// 觀測數據元素
Observer.prototype.observeArray = function (items) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
Observer 修改完畢後,我們再看看 Watcher , 只需要改動其 update 函數,
Watcher.prototype.update = function (dep) {
console.log('2.update')
const value = this.get()
const oldValue = this.value
this.value = value
if (value !== this.value || value !== null) {
this.cb.call(this.vm, value, oldValue)
// 如果沒有此函數, 會導致重復調用 $watch 回調函數。
// 原因:數組變異過了,並對新數組也進行了觀察,應該移除舊的觀察者
dep.subs.shift()
}
}
結果:
const vm = new Vue({
data: {
b: [{a: 'a'}, {b: 'b'}]
}
})
vm.$watch('b', (val) => {
console.log('------我看到你們了-----')
})
vm.b.push({c: 'c'})
vm.b.pop({c: 'c'})
vm.b.push({c: 'c'})
// 結果:
// console.log('------我看到你們了-----')
// console.log('------我看到你們了-----')
// console.log('------我看到你們了-----')
總結
至此,我們已經實現對數組變動的檢測。主要使用了Object.create()函數。希望這篇文章的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。