vue如何監聽數組的變化


export function def (obj: Object, key: string, val: any, enumerable?: boolean) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true
  })
}
observeArray (items: Array<any>) {
  for (let i = 0, l = items.length; i < l; i++) {
    observe(items[i])
  }
}

源碼:import { def } from '../util/index'

 const arrayProto = Array.prototype
// 創建arrayMehtods對象,指向Array的原型 export const arrayMethods
= Object.create(arrayProto) const methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method const original = arrayProto[method]
 // 監聽數組原型上的方法 def(arrayMethods, method,
function mutator (...args) { const result = original.apply(this, args) const ob = this.__ob__ let inserted
  // 如果遇到push,unshift,splice方法,這些新增元素的方法,Object.defineProperty不會自動檢測到,需要重新使用數據劫持進行檢測。
switch (method) { case 'push': case 'unshift': inserted = args break case 'splice': inserted = args.slice(2) break }
  // 如果發生了新增,就重新進行數據劫持
if (inserted) ob.observeArray(inserted) // notify change
  //通知dom進行更新
ob.dep.notify() return result }) })

 1.重寫了操作數組的方法,在數組的push,unshift,splice改變數組長度的方法中,通過Object.definePeoperty劫持新增的數組的數據,實現雙向數據綁定。同時更新demo


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM