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