Vue源码阅读笔记—— 数组是如何做到响应式的

456 阅读1分钟

前言

所看的源码版本是:"version": "2.6.14"

上篇文章我们学习了vue2中对象是如果观察到变化的,那这一篇我们学习下数组是怎样做到的。

源码笔记

Observer类中(src\core\observer\index.js),我们重点看数组处理部分:

export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that have this object as root $data

  constructor (value: any) {
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
    def(value, '__ob__', this)
    // 主要看数组中这个if的处理逻辑
    if (Array.isArray(value)) {
      if (hasProto) {
        protoAugment(value, arrayMethods)
      } else {
        copyAugment(value, arrayMethods, arrayKeys)
      }
      this.observeArray(value)
    } else {
      this.walk(value)
    }
  }
  ......

  /**
   * Observe a list of Array items.
   */
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

对于数组先判断能不能使用__proto__来分别调用protoAugmentcopyAugment

export const hasProto = '__proto__' in {}

function protoAugment (target, src: Object) {
  /* eslint-disable no-proto */
  target.__proto__ = src
  /* eslint-enable no-proto */
}

function copyAugment (target: Object, src: Object, keys: Array<string>) {
  for (let i = 0, l = keys.length; i < l; i++) {
    const key = keys[i]
    def(target, key, src[key])
  }
}

然后我们看下上面传参的arrayMethodsarrayKeys

arrayMethods主要在array.js (src\core\observer\array.js)中:

/*
 * 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)

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
    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
  })
})

const arrayKeys = Object.getOwnPropertyNames(arrayMethods)
  • arrayProto拿到数组原型对象,然后arrayMethods通过Object.create(arrayProto)实现了继承。

  • __proto__是可以使用的时候,我们就将arrayMethods放到原型上面去;如果不可用,我们通过循环通过def,添加到属性上面去。

  • 然后通过observeArray方法,遍历数组给每一项添加观察。

总结

针对数组没有使用Object.defineProperty去监听每一项,会带来一些性能问题;而是通过对数组的7个方法进行重写来进行观察。