Vue2.0源码阅读笔记(三):计算属性

1,931 阅读5分钟

  计算属性是基于响应式依赖进行缓存的,只有在相关响应式依赖发生改变时才会重新求值,这种缓存机制在求值消耗比较大的情况下能够显著提高性能。

一、计算属性初始化

  Vue 在做数据初始化时,通过 initComputed() 方法初始化计算属性。

const computedWatcherOptions = { lazy: true }

function initComputed (vm: Component, computed: Object) {
  const watchers = vm._computedWatchers = Object.create(null)
  const isSSR = isServerRendering()

  for (const key in computed) {
    const userDef = computed[key]
    const getter = typeof userDef === 'function' ? userDef : userDef.get
    if (process.env.NODE_ENV !== 'production' && getter == null) {
      warn(`Getter is missing for computed property "${key}".`, vm)
    }

    if (!isSSR) {
      watchers[key] = new Watcher(vm, getter || noop,
        noop, computedWatcherOptions)
    }

    if (!(key in vm)) {
      defineComputed(vm, key, userDef)
    } else if (process.env.NODE_ENV !== 'production') {
      if (key in vm.$data) {
        warn(`The computed property "${key}" is already defined in data.`, vm)
      } else if (vm.$options.props && key in vm.$options.props) {
        warn(`The computed property "${key}" is already defined as a prop.`, vm)
      }
    }
  }
}

  首先将变量 watchers 与变量 _computedWatchers 同时指向一个空对象,该对象用来存储所有计算属性的观察者。接着定义变量 isSSR 用来标识是否为服务器端渲染。
  然后对选项 computed 中的属性遍历,将属性赋值给 userDef 变量。计算属性有两种写法:函数、对象。如果是对象的话则必须要有 get(), set() 方法可以不实现。使用 getter 变量指向能够获取值的函数。
  在服务器端渲染时,使用计算属性的方式和使用方法基本一样。在非服务器端渲染时,生成该计算属性的观察者添加到变量 watchers 与变量 _computedWatchers 对应的属性上。
  最后检查 Vue 实例对象上有没有与计算属性同名的属性,因为不管选项 props 、data ,还是选项 computed 中的数据经过处理最终都会添加到 Vue 实例对象上。如果没有重复,则调用 defineComputed() 方法将计算属性处理之后添加到 Vue 实例对象上。

二、定义计算属性

  defineComputed() 函数的功能是将计算属性转化为 Vue 实例对象的访问器属性。

export function defineComputed (target: any, key: string,
  userDef: Object | Function
) {
  const shouldCache = !isServerRendering()
  if (typeof userDef === 'function') {
    sharedPropertyDefinition.get = shouldCache
      ? createComputedGetter(key)
      : createGetterInvoker(userDef)
    sharedPropertyDefinition.set = noop
  } else {
    sharedPropertyDefinition.get = userDef.get
      ? shouldCache && userDef.cache !== false
        ? createComputedGetter(key)
        : createGetterInvoker(userDef.get)
      : noop
    sharedPropertyDefinition.set = userDef.set || noop
  }
  if (process.env.NODE_ENV !== 'production' &&
      sharedPropertyDefinition.set === noop) {
    sharedPropertyDefinition.set = function () {
      warn(
        `Computed property "${key}" was assigned to but it has no setter.`,
        this
      )
    }
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

  在非服务器端渲染时,若选项中计算属性是函数形式,则将 set() 方法设为空;若是对象形式,对象中提供 set() 方法,则采用该方法作为访问器属性的 set() 方法,如果没有提供,则 set() 方法为空。最后在 set() 方法为空的情况下,重写该方法,使其在非生产环境下访问器属性被设置时提示警告信息。
  计算属性的 get() 方法 为 createComputedGetter() 的返回值,该返回值为 computedGetter() 函数。

function createComputedGetter (key) {
  return function computedGetter () {
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      if (watcher.dirty) {
        watcher.evaluate()
      }
      if (Dep.target) {
        watcher.depend()
      }
      return watcher.value
    }
  }
}

  比如传入 computed 选项如下:

data () {
  retrun {
    a: 1
  }
}

computed: {
  b () {
    retrun a * 2
  }
}

  经过计算属性初始化处理之后,变成 Vue 实例对象 vm 上的属性:

vm.b = Object.defineProperty(vm, 'b', {
  enumerable: true,
  configurable: true,
  get () {
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      if (watcher.dirty) {
        watcher.evaluate()
      }
      if (Dep.target) {
        watcher.depend()
      }
      return watcher.value
    }
  },
  set () {
    warn(
      `Computed property "${key}" was assigned to but it has no setter.`,
      this
    )
  }
})

三、计算属性观察者

  上面例子中的计算属性 b 在初始化时创建的观察者对象 watcherB 如下:

watcherB = {
  vm: vm,
  lazy: true,
  deep: false,
  user: false,
  sync: false,
  cb: function () {},
  uid: 1,
  active: true,
  dirty: true,
  deps: [],
  newDeps: [],
  depIds: new Set(),
  newDepIds: new Set(),
  expression: 'function() {\n return a * 2 \n}',
  getter: function() { return a * 2 },
  value: undefined
}

  在开发中最常见的是在模板中使用计算属性,该种情况下会先将模板转换成渲染函数,然后生成渲染函数观察者,在此过程中,会读取计算属性。

(1)、读取计算属性时的函数执行情况

  在计算属性 b 被读取时,会调用访问器属性的 get() 方法。

get () {
  const watcher = this._computedWatchers && this._computedWatchers[key]
  if (watcher) {
    if (watcher.dirty) {
      watcher.evaluate()
    }
    if (Dep.target) {
      watcher.depend()
    }
    return watcher.value
  }
}

  此时,访问器属性的 get() 方法中的 watcher 为 watcherB ,Dep.target 为渲染函数观察者,记为 renderWatcher。函数执行的顺序如下:
1、watcherB.dirty 为 true ,所以先执行 watcherB.evaluate() 。在该方法中首先调用 watcherB.get() 。
2、watcherB.get() 先将 Dep.target 引用变量指向 watcherB ,然后 调用 watcherB.getter() 。
3、watcherB.getter() 会触发响应式数据 a 的 get() ,在该方法中调用 a 闭包引用的的变量 dep 的 depend() 方法。
4、在 dep.depend() 会调用 watcherB.addDep(dep)。
5、watcherB.addDep(dep)主要做三件事:将 dep.id 添加到 watcherB.newDepIds 集合中、将 dep 添加到 watcherB.newDeps 数组中、调用dep.addSub()方法。
6、dep.addSub() 方法会将 watcherB 添加到响应式数据 a 闭包引用的变量 dep 的 subs 数组中。
7、然后接着执行 watcherB.get(),首先将 Dep.target 的值设置为 renderWatcher ,再执行 watcherB.cleanupDeps()。
8、watcherB.cleanupDeps() 会将 watcherB.newDepIds、watcherB.newDeps 中的数据分别复制到 watcherB.depIds、watcherB.deps中,然后再清空 watcherB.newDepIds、watcherB.newDeps。
9、然后接着执行 watcherB.evaluate(),将 watcherB.dirty 设置为 false。
10、然后接着执行计算属性 b 的 get() 方法,调用 watcherB.depend()。
11、watcherB.depend() 方法循环 watcherB.deps 数组,调用数据 a 闭包引用的 dep 的 depend() 方法。此时的 Dep.target 的值为 renderWatcher,dep.depend() 将渲染函数观察者添加到数据 a 闭包引用的 dep 中。

(2)、计算属性读取总结

  抛开较为繁琐的执行过程不说,当第一次读取计算属性时,主要做了以下几方面的事情:

1、将计算属性观察者收集进相关响应式数据的依赖容器中。
2、将使用计算属性的渲染函数观察者收集进相关响应式数据的依赖容器中。
3、将计算属性观察者的 dirty 属性设置为 false。若 dirty 为 true ,读取计算属性时会执行第1条操作。

(3)、依赖改变时计算属性重新求值

  当计算属性依赖的响应式数据发生改变时,会触发依赖容器中的依赖,此时计算属性以及使用计算属性的渲染函数都会重新求值。

四、总结

  Vue在数据初始化时会将计算属性改造成实例对象上的访问器属性,同时生成对应的计算属性观察者。
  在初次读取计算属性时,会将计算属性观察者、读取计算属性的渲染函数观察者作为依赖收集到相关响应式数据的依赖容器中。再次读取计算属性时,仅仅将读取计算属性的渲染函数观察者收集到依赖容器中,因为计算属性与响应式数据的依赖关系没有发生变化,此时计算属性观察者已作为依赖被收集,不必重复添加。
  当相关响应式数据改变时,对应的计算属性以及渲染函数都会发生改变。
  计算属性就像响应式数据与渲染函数观察者之间的“桥梁”。如果渲染函数直接使用响应式数据,则只需要收集渲染函数观察者,计算属性存在的意义在于对响应式数据进行操作,而且不用每次都经过计算求值。

如需转载,烦请注明出处:juejin.cn/post/684490…