流程图

initComputed.png

回顾用法

计算属性的结果会被缓存,除非依赖的响应式属性变化才会重新计算。
根据官方文档的使用示例,我们回顾一下计算属性的用法:

  1. var vm = new Vue({
  2. data: { a: 1 },
  3. computed: {
  4. // 仅读取
  5. aDouble: function () {
  6. return this.a * 2
  7. },
  8. // 读取和设置
  9. aPlus: {
  10. get: function () {
  11. return this.a + 1
  12. },
  13. set: function (v) {
  14. this.a = v - 1
  15. }
  16. }
  17. }
  18. })
  19. vm.aPlus // => 2
  20. vm.aPlus = 3
  21. vm.a // => 2
  22. vm.aDouble // => 4

computed选项中的属性值可以是一个函数,那么该函数默认为取值器getter,用于仅读取数据;还可以是一个对象,对象里面有取值器getter和存值器setter,用于读取和设置数据。
我们知道computed计算属性是依赖于其它响应式变量的,因此我们分析computed的时候会分为两个步骤:computed初始化和computed更新。

computed初始化

initComputed函数分析

initComputed函数的定义位于源码的src/core/instance/state.js中,如下:

  1. const computedWatcherOptions = { lazy: true }
  2. function initComputed (vm: Component, computed: Object) {
  3. // $flow-disable-line
  4. const watchers = vm._computedWatchers = Object.create(null)
  5. // computed properties are just getters during SSR
  6. const isSSR = isServerRendering()
  7. for (const key in computed) {
  8. const userDef = computed[key]
  9. const getter = typeof userDef === 'function' ? userDef : userDef.get
  10. if (process.env.NODE_ENV !== 'production' && getter == null) {
  11. warn(
  12. `Getter is missing for computed property "${key}".`,
  13. vm
  14. )
  15. }
  16. if (!isSSR) {
  17. // create internal watcher for the computed property.
  18. watchers[key] = new Watcher(
  19. vm,
  20. getter || noop,
  21. noop,
  22. computedWatcherOptions
  23. )
  24. }
  25. // component-defined computed properties are already defined on the
  26. // component prototype. We only need to define computed properties defined
  27. // at instantiation here.
  28. if (!(key in vm)) {
  29. defineComputed(vm, key, userDef)
  30. } else if (process.env.NODE_ENV !== 'production') {
  31. if (key in vm.$data) {
  32. warn(`The computed property "${key}" is already defined in data.`, vm)
  33. } else if (vm.$options.props && key in vm.$options.props) {
  34. warn(`The computed property "${key}" is already defined as a prop.`, vm)
  35. }
  36. }
  37. }
  38. }

在initComputed()方法中,首先定义了一个_computedWatchers的变量并将其赋值为空对象,这个变量的作用是缓存当前实例所有计算属性的watcher实例。

  1. const watchers = vm._computedWatchers = Object.create(null)

然后遍历用户写的computed选项中的每一项属性,首先获取到每一项的属性值,记作userDef
判断userDef是不是一个函数,如果是函数,则将该函数默认为取值器getter,将其赋值给变量getter;
如果不是函数,则说明是一个对象,则取对象中的get属性作为取值器赋给变量getter。如下:

  1. const userDef = computed[key]
  2. const getter = typeof userDef === 'function' ? userDef : userDef.get

接着判断在非生产环境下如果上面两种情况取到的取值器不存在,则抛出警告:提示用户计算属性必须有取值器。如下:

  1. if (process.env.NODE_ENV !== 'production' && getter == null) {
  2. warn(
  3. `Getter is missing for computed property "${key}".`,
  4. vm
  5. )
  6. }

接着判断如果不是在SSR(服务端)渲染环境下,则为 computed 选项中的每一项属性创建一个 watcher实例,并将当前循环到的的属性名作为键,创建的watcher实例作为值,存入 watchers 对象中。如下:

  1. if (!isSSR) {
  2. // create internal watcher for the computed property.
  3. watchers[key] = new Watcher(
  4. vm,
  5. getter || noop,
  6. noop,
  7. computedWatcherOptions
  8. )
  9. }

其中,上面代码中创建 watcher实例时所传入的 getter就是取到用户所写的该计算属性的取值器。而 computedWatcherOptions参数如下:

  1. const computedWatcherOptions = { lazy: true }

这个参数是用来标记当前所创建的 watcher实例是一个计算属性的 watcher 实例,给它一个 { lazy: true } 的配置,这是为将来计算属性值缓存做准备。众所周知,计算属性有个特点就是它可以缓存当前的计算结果,也就是说如果某个计算属性所依赖的数据没有发生变化,那么该计算属性就不会去重复计算,会直接获取上一次的计算结果。这个 { lazy: true } 就是给计算属性做缓存时用的。
最后,判断当前循环到的的属性名是否存在于当前实例 vm上,如果不存在,则调用 defineComputed 函数为实例 vm 上设置计算属性。
如果在还需要判断当前遍历的computed是否和props、data命名冲突,如果冲突则提示错误。

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

defineComputed函数分析

defineComputed函数的定义位于源码的 src/core/instance/state.js 中,如下:

  1. const sharedPropertyDefinition = {
  2. enumerable: true,
  3. configurable: true,
  4. get: noop,
  5. set: noop
  6. }
  7. export function defineComputed (
  8. target: any,
  9. key: string,
  10. userDef: Object | Function
  11. ) {
  12. const shouldCache = !isServerRendering()
  13. if (typeof userDef === 'function') {
  14. sharedPropertyDefinition.get = shouldCache
  15. ? createComputedGetter(key)
  16. : createGetterInvoker(userDef)
  17. sharedPropertyDefinition.set = noop
  18. } else {
  19. sharedPropertyDefinition.get = userDef.get
  20. ? shouldCache && userDef.cache !== false
  21. ? createComputedGetter(key)
  22. : createGetterInvoker(userDef.get)
  23. : noop
  24. sharedPropertyDefinition.set = userDef.set || noop
  25. }
  26. if (process.env.NODE_ENV !== 'production' &&
  27. sharedPropertyDefinition.set === noop) {
  28. sharedPropertyDefinition.set = function () {
  29. warn(
  30. `Computed property "${key}" was assigned to but it has no setter.`,
  31. this
  32. )
  33. }
  34. }
  35. Object.defineProperty(target, key, sharedPropertyDefinition)
  36. }

该函数接受3个参数,分别是:target 、 key 和 userDef 。其作用是为 target 上定义一个属性 key ,并且属性 key 的 getter 和 setter 根据 userDef 的值来设置。
defineComputed()方法的逻辑很简单,根据不同的类型的computed,对sharedPropertyDefinition的get和set进行赋值。
下面我们就来看一下该函数的具体逻辑。
首先定义了变量 sharedPropertyDefinition ,它是一个默认的属性描述符,如下:

  1. const sharedPropertyDefinition = {
  2. enumerable: true,
  3. configurable: true,
  4. get: noop,
  5. set: noop
  6. }

在函数内部定义了变量 shouldCache ,用于标识计算属性是否应该有缓存。
该变量的值是当前环境是否为非服务端渲染环境,如果是非服务端渲染环境则该变量为 true 。也就是说,只有在非服务端渲染环境下计算属性才应该有缓存。如下:

  1. const shouldCache = !isServerRendering()

接着,判断如果 userDef 是一个函数,则该函数默认为取值器 getter ,此处在非服务端渲染环境下并没有直接使用 userDef 作为 getter ,而是调用 createComputedGetter 函数(关于该函数下面会介绍)创建了一个 getter ,这是因为 userDef 只是一个普通的 getter,它并没有缓存功能,所以我们需要额外创建一个具有缓存功能的 getter 。
由于用户没有设置 setter 函数,所以将 sharedPropertyDefinition.set 设置为 noop 。如下:

  1. /*创建计算属性的getter*/
  2. if (typeof userDef === 'function') {
  3. sharedPropertyDefinition.get = shouldCache
  4. ? createComputedGetter(key)
  5. : createGetterInvoker(userDef)
  6. /*
  7. 当userDef是一个function的时候是不需要setter的,所以这边给它设置成了空函数。
  8. 因为计算属性默认是一个function,只设置getter。
  9. 当需要设置setter的时候,会将计算属性设置成一个对象。
  10. */
  11. sharedPropertyDefinition.set = noop
  12. }

如果 userDef 不是一个函数,那么就将它当作对象处理。
在设置 sharedPropertyDefinition.get 的时候先判断 userDef.get 是否存在,如果不存在,则将其设置为 noop ,如果存在,则同上面一样,在非服务端渲染环境下并且用户没有明确的将 userDef.cache设置为 false 时调用 createComputedGetter 函数创建一个 getter 赋给 sharedPropertyDefinition.get 。然后设置 sharedPropertyDefinition.set为 userDef.set 函数。如下:

  1. sharedPropertyDefinition.get = userDef.get
  2. ? shouldCache && userDef.cache !== false
  3. ? createComputedGetter(key)
  4. : createGetterInvoker(userDef.get)
  5. : noop
  6. /*如果有设置set方法则直接使用,否则赋值空函数*/
  7. sharedPropertyDefinition.set = userDef.set || noop

接着,再判断在非生产环境下如果用户没有设置 setter 的话,那么就给 setter 一个默认函数,这是为了防止用户在没有设置 setter 的情况下修改计算属性,从而为其抛出警告,如下:

  1. if (process.env.NODE_ENV !== 'production' &&
  2. sharedPropertyDefinition.set === noop) {
  3. sharedPropertyDefinition.set = function () {
  4. warn(
  5. `Computed property "${key}" was assigned to but it has no setter.`,
  6. this
  7. )
  8. }
  9. }

最后调用 Object.defineProperty 方法将属性 key 绑定到 target 上,其中的属性描述符就是上面设置的 sharedPropertyDefinition 。如此以来,就将计算属性绑定到实例 vm 上了。

  1. Object.defineProperty(target, key, sharedPropertyDefinition)

以上就是 defineComputed 函数的所有逻辑。另外,我们发现,计算属性有没有缓存及其响应式貌似主要在于是否将 getter 设置为 createComputedGetter 函数的返回结果。
那么接下来,我们就对这个 createComputedGetter 函数一探究竟。

createComputedGetter函数分析

createComputedGetter函数的定义位于源码的src/core/instance/state.js中,如下:

  1. function createComputedGetter (key) {
  2. return function computedGetter () {
  3. const watcher = this._computedWatchers && this._computedWatchers[key]
  4. if (watcher) {
  5. /*实际是脏检查,在计算属性中的依赖发生改变的时候dirty会变成true,
  6. 在get的时候重新计算计算属性的输出值*/
  7. if (watcher.dirty) {
  8. watcher.evaluate()
  9. }
  10. /*依赖收集*/
  11. if (Dep.target) {
  12. watcher.depend()
  13. }
  14. return watcher.value
  15. }
  16. }
  17. }

createComputedGetter()函数是一个高阶函数,其内部返回了一个叫做 computedGetter 的函数,所以其实是将 computedGetter 函数赋给了 sharedPropertyDefinition.get。当获取计算属性的值时会执行属性的 getter,而属性的 getter 就是 sharedPropertyDefinition.get ,也就是说最终执行的 computedGetter 函数。
在 computedGetter 函数内部,首先获取之前创建好的存储在实例上 _computedWatchers 属性中当前计算属性名 key 所对应的 watcher 实例,如下:

  1. function createComputedGetter (key) {
  2. return function computedGetter () {
  3. const watcher = this._computedWatchers && this._computedWatchers[key]
  4. if (watcher) {
  5. /*实际是脏检查,在计算属性中的依赖发生改变的时候dirty会变成true,
  6. 在get的时候重新计算计算属性的输出值*/
  7. if (watcher.dirty) {
  8. watcher.evaluate()
  9. }
  10. /*依赖收集*/
  11. if (Dep.target) {
  12. watcher.depend()
  13. }
  14. return watcher.value
  15. }
  16. }
  17. }

如果 watcher 实例存在,则判断该实例上的 dirty 属性是否为 true ,如果为 true ,即表明当前计算属性的计算结果发生了变化,则立即调用实例上的 evaluate 方法获取最新的计算结果,在 evaluate 方法内部会将最新的计算结果赋值给实例上的 value 属性(在下面会介绍),如下:

  1. if (watcher) {
  2. /*实际是脏检查,在计算属性中的依赖发生改变的时候dirty会变成true,
  3. 在get的时候重新计算计算属性的输出值*/
  4. if (watcher.dirty) {
  5. watcher.evaluate()
  6. }
  7. //...省略代码
  8. }

如果当前有需要收集的依赖,则调用实例上的 depend 方法进行依赖收集,如下:

  1. if (Dep.target) {
  2. watcher.depend()
  3. }

最后,返回实例上的 value 属性,该属性即为当前计算属性的最终计算结果。
那么 watcher 实例上的 depend 方法和 evaluate 方法又是什么呢?

depend和evaluate

看一下 Watcher 类的定义,如下:

  1. export default class Watcher {
  2. constructor (vm,expOrFn,cb,options,isRenderWatcher) {
  3. if (options) {
  4. this.lazy = !!options.lazy
  5. } else {
  6. this.lazy = false
  7. }
  8. this.dirty = this.lazy
  9. /*把表达式expOrFn解析成getter*/
  10. if (typeof expOrFn === 'function') {
  11. this.getter = expOrFn
  12. } else {
  13. this.getter = parsePath(expOrFn)
  14. if (!this.getter) {
  15. this.getter = noop
  16. }
  17. }
  18. this.value = this.lazy
  19. ? undefined
  20. : this.get()
  21. }
  22. evaluate () {
  23. this.value = this.get()
  24. this.dirty = false
  25. }
  26. /**
  27. * Depend on this watcher. Only for computed property watchers.
  28. */
  29. depend () {
  30. if (this.dep && Dep.target) {
  31. this.dep.depend()
  32. }
  33. }
  34. // 当依赖发生改变的时候触发回调。
  35. update () {
  36. /* istanbul ignore else */
  37. if (this.lazy) {
  38. this.dirty = true
  39. } else if (this.sync) {
  40. /*同步则执行run直接渲染视图*/
  41. this.run()
  42. } else {
  43. /*异步推送到观察者队列中,下一个tick时调用。*/
  44. queueWatcher(this)
  45. }
  46. }
  47. }

可以看到,在实例化 Watcher 类的时候,第四个参数传入了一个对象 computedWatcherOptions = { lazy: true } ,该对象中的 lazy 属性标志着这个 watcher 实例是计算属性的 watcher 实例,同时类中还定义了 this.dirty 属性用于标志计算属性的返回值是否有变化,计算属性的缓存就是通过这个属性来判断的,每当计算属性依赖的数据发生变化时,会将 this.dirty 属性设置为 true ,这样下一次读取计算属性时,会重新计算结果返回,否则直接返回之前的计算结果。

当我们在组件中定义了一个计算属性 name 并且在视图中使用了该属性时,视图第一次刷新会去获取 name 的属性值,此时就会调用该属性值的 getter 方法,这个 getter 方法就是 computedGetter ,如下:

  1. function computedGetter () {
  2. const watcher = this._computedWatchers && this._computedWatchers[key]
  3. if (watcher) {
  4. if (watcher.dirty) {
  5. watcher.evaluate()
  6. }
  7. if (Dep.target) {
  8. watcher.depend()
  9. }
  10. return watcher.value
  11. }
  12. }

第一次 watcher.dirty 值默认为 true ,此时就会去调用 watcher.evaluate 方法,在该方法中会调用 watcher.get 方法获取当前计算属性值并将其赋值给 watcher.value 属性,同时将 watcher.dirty改为 false ,如下:

  1. evaluate () {
  2. this.value = this.get()
  3. this.dirty = false
  4. }

接着,当计算属性中用到的数据发生变化时,计算属性的 watcher 实例就会执行 watcher.update 方法,在 update 方法中会判断 this.lazy 是否为 true,如果为 true 则表明这个 watcher 实例是计算属性的 watcher 实例,那么就将 watcher.dirty 变为 true ,这样当视图再次获取 name 时,就会重新调用 watcher.evaluate 方法来获取最新的计算属性值。

如果计算属性中用到的数据没有发生变化,那么计算属性的 watcher 实例的 watcher.update 方法就不会执行,那么 watcher.dirty 就不会被变为 true ,依然为 false ,那么当视图再次获取 name 时,就不会调用 watcher.evaluate 方法,直接返回已有的 watcher.value ,即上一次的计算结果。

这就是计算属性为什么会有缓存计算结果的原因。

computed更新

在介绍完了computed的初始化后,我们在来看computed的更新过程,以下面例子为例:

  1. export default {
  2. template: `
  3. <div>{{fullName}}</div>
  4. <button @click="change">change</button>
  5. `
  6. data () {
  7. return {
  8. total: 0,
  9. firstName: 'first',
  10. lastName: 'last'
  11. }
  12. },
  13. computed: {
  14. fullName () {
  15. if (this.total > 0) {
  16. return this.firstName + this.lastName
  17. } else {
  18. return 'pleace click'
  19. }
  20. }
  21. },
  22. methods: {
  23. change () {
  24. this.total++
  25. }
  26. }
  27. }

因为total、firstName和lastName全部为响应式变量,所以fullName这个计算属性初始化的时候,此时total值为0,fullName计算属性有两个Watcher,其中一个是计算属性watcher,另外一个是渲染watcher。当点击按钮触发事件后,会触发total属性的setter方法,进而调用一个叫做notify的方法。

  1. set: function reactiveSetter (newVal) {
  2. // 省略
  3. dep.notify()
  4. }

其中notify()是定义在Dep类中的一个方法:

  1. export default class Dep {
  2. constructor () {
  3. this.subs = []
  4. }
  5. notify () {
  6. // stabilize the subscriber list first
  7. const subs = this.subs.slice()
  8. if (process.env.NODE_ENV !== 'production' && !config.async) {
  9. // subs aren't sorted in scheduler if not running async
  10. // we need to sort them now to make sure they fire in correct
  11. // order
  12. subs.sort((a, b) => a.id - b.id)
  13. }
  14. for (let i = 0, l = subs.length; i < l; i++) {
  15. subs[i].update()
  16. }
  17. }
  18. }
  • subs就是我们收集起来的watcher,它是一个数组,对应上面案例的话它是一个长度为2的数组并且其中一个为render watcher。
  • 在notify()方法调用时,会遍历subs数组,然后依次调用当前watcher的update方法。其中update方法是定义在Watcher类中的一个实例方法,代码如下:
    1. class Watcher {
    2. // 省略其它
    3. update () {
    4. /* istanbul ignore else */
    5. if (this.lazy) {
    6. this.dirty = true
    7. } else if (this.sync) {
    8. this.run()
    9. } else {
    10. queueWatcher(this)
    11. }
    12. }
    13. }
    当第一次遍历时,此时的watcher为计算属性watcher,我们已经在前面介绍过计算属性watcher它的this.lazy值为true,因此会进行this.dirty = true。
    当第二次遍历时,此时的watcher为渲染watcher,对于渲染watcher而言,它的lazy值为false,this.sync为false,因此会调用queueWatcher()方法。我们目前不需要知道queueWatcher是怎么实现的,只需要知道queueWatcher()方法在调用时,会触发updateComponent()方法:
    1. updateComponent = () => {
    2. vm._update(vm._render(), hydrating)
    3. }
    updateComponent()方法调用了vm._update方法,而这个方法的作用就是重新进行组件渲染,在组件渲染的过程中,会再次读取fullName的值,也就是说会调用下面这段代码:
    1. fullName () {
    2. if (this.total > 0) {
    3. return this.firstName + this.lastName
    4. } else {
    5. return 'pleace click'
    6. }
    7. }
    因为此时的total值为1,所以会返回this.firstName + this.lastName的值,而firstName和lastName又是定义在data中的响应式变量,会依次触发firstName和lastName的getter,然后进行依赖收集。
    在组件渲染完毕后,fullName的依赖数组subs此时会有四个watcher,分别是三个计算属性watcher和一个渲染watcher。无论这三个计算属性watcher哪一个值更新了,都会再出重复以上的流程,这就是computed更新的过程。