Vue源码解读之Vue中是如何检测数组变化的

前言

  • 通过上一篇文章,我们知道了Vue初始化data的响应式原理,只讲到了对象是如何通过defineReactive 方法对data属性创建监测的,而数组则只是略带过,下边我们就通过源码来捋一下

首先看回这个判断 src/core/observer/index.js Observer 类构造函数

// 我们看回这段代码
 if (Array.isArray(value)) { // 是数组
      if (hasProto) {
        protoAugment(value, arrayMethods) // 改写数组原型方法
      } else {
        copyAugment(value, arrayMethods, arrayKeys) // 复制数组已有方法
      }
      this.observeArray(value) // 深度观察数组中的每一项 , observeArray 往下看
    } else { 
      this.walk(value) //是对象则重新定义对象类型数据 (前章讲过)
    }
 }

protoAugment 方法 改写原型方法,把原型改写指向 arrayMethods

/**
 * Augment a target Object or Array by intercepting
 * the prototype chain using __proto__
 */
function protoAugment (target, src: Object) {
  /* eslint-disable no-proto */
  target.__proto__ = src
  /* eslint-enable no-proto */
}

observeArray 方法 主要是遍历数组,然后调用 observer 判断是否已经被监听,没被监听则 new Observer 类 创建监听 ,前边有讲过 ;

 /**
   * Observe a list of Array items.
   */
  observeArray (items: Array<any>) { // 是数组则遍历数组,走进observer方法查看是否被监听
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])  // 观测数组中的每一项 
    }
  }

数组改写原型和通知观察者更新的地方 src/core/observer/array.js , 整个 js 文件内容不多,主要做了几件事

  • 创建数组原型,赋值给 arrayMethods
  • 重写数组原型方法给 arrayMethods 并修改 this
  • 对数组改变的数据进行观测,递归遍历 方法实体往上看10行 observeArray
  • 通知 wachter 更新视图
/*
 * not type checking this file because flow doesn't play well with
 * dynamically accessing methods on Array prototype
 */

import { def } from '../util/index'

const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto) // 创建一个数组原型赋值给 arrayMethods

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) // 原生的方法修改this
    const ob = this.__ob__
    let inserted
    switch (method) {
      case 'push':
      case 'unshift':
        inserted = args
        break
      case 'splice':
        inserted = args.slice(2)
        break
    }
    if (inserted) ob.observeArray(inserted) // 对插入的数据再次进行观测
    // notify change
    ob.dep.notify()  // 通知视图更新
    return result
  })
})

总结

Vue 将 data 中的数组,通过函数劫持的方式,进行了原型链重写;指向了自己定义的数组原型方法,这样当调用数组 api 时,可以通知依赖更新.如果数组中包含着引用类型;会对数组中的引用类型再次进行监控。

发布了22 篇原创文章 · 获赞 44 · 访问量 8236

猜你喜欢

转载自blog.csdn.net/HiSen_CSDN/article/details/104830369
今日推荐