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

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

1、计算属性初始化

  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 实例对象上。
缓存

2、定义计算属性

  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 上的属性:
oop

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
    )
  }
})
复制代码

3、计算属性观察者

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

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() 方法。
ui

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。函数执行的顺序以下:
一、watcherB.dirty 为 true ,因此先执行 watcherB.evaluate() 。在该方法中首先调用 watcherB.get() 。
二、watcherB.get() 先将 Dep.target 引用变量指向 watcherB ,而后 调用 watcherB.getter() 。
三、watcherB.getter() 会触发响应式数据 a 的 get() ,在该方法中调用 a 闭包引用的的变量 dep 的 depend() 方法。
四、在 dep.depend() 会调用 watcherB.addDep(dep)。
五、watcherB.addDep(dep)主要作三件事:将 dep.id 添加到 watcherB.newDepIds 集合中、将 dep 添加到 watcherB.newDeps 数组中、调用dep.addSub()方法。
六、dep.addSub() 方法会将 watcherB 添加到响应式数据 a 闭包引用的变量 dep 的 subs 数组中。
七、而后接着执行 watcherB.get(),首先将 Dep.target 的值设置为 renderWatcher ,再执行 watcherB.cleanupDeps()。
八、watcherB.cleanupDeps() 会将 watcherB.newDepIds、watcherB.newDeps 中的数据分别复制到 watcherB.depIds、watcherB.deps中,而后再清空 watcherB.newDepIds、watcherB.newDeps。
九、而后接着执行 watcherB.evaluate(),将 watcherB.dirty 设置为 false。
十、而后接着执行计算属性 b 的 get() 方法,调用 watcherB.depend()。
十一、watcherB.depend() 方法循环 watcherB.deps 数组,调用数据 a 闭包引用的 dep 的 depend() 方法。此时的 Dep.target 的值为 renderWatcher,dep.depend() 将渲染函数观察者添加到数据 a 闭包引用的 dep 中。

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

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

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

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

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

4、总结

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

如需转载,烦请注明出处:juejin.im/post/5cc159…

相关文章
相关标签/搜索