blog icon indicating copy to clipboard operation
blog copied to clipboard

Vue的computed是如何实现缓存的?

Open rudyxu1102 opened this issue 4 years ago • 0 comments

介绍

computed,即计算属性。当其依赖的属性的值发生变化的时,计算属性会重新计算,否则使用缓存中的属性值。

基础例子

<div id="example">
  <p>My Name is: "{{ fullName }}"</p>
</div>
var vm = new Vue({
  el: '#example',
  data: {
    firstName: 'rudy',
    lastName: 'dong'
  },
  computed: {
    // 计算属性的 getter
    fullName: function () {
      return this.firstName + ' ' + this.lastName
    }
  }
})

源码分析

下面我们带着一些问题去看一下computed的源码:

  • 如何实现缓存?
  • 缓存值存在哪里?

初始化computed

调用initComputed,传入computed对象。

// https://github.com/vuejs/vue/blob/master/src/core/instance/state.js#L48
export function initState (vm: Component) {
  vm._watchers = []
  const opts = vm.$options
  if (opts.props) initProps(vm, opts.props)
  if (opts.methods) initMethods(vm, opts.methods)
  if (opts.data) {
    initData(vm)
  } else {
    observe(vm._data = {}, true /* asRootData */)
  }
  if (opts.computed) initComputed(vm, opts.computed)
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch)
  }
}

initComputed方法中遍历computed对象,为每个计算属性实例一个监听器watcher,并传入{lazy: true},然后判断data是否已经存在同名属性,如果不存在同名属性,就调用defineComputed方法

// https://github.com/vuejs/vue/blob/master/src/core/instance/state.js#L163

const computedWatcherOptions = { lazy: true }

function initComputed (vm: Component, computed: Object) {
  const watchers = vm._computedWatchers = Object.create(null)
  // computed properties are just getters during SSR
  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) {
      // create internal watcher for the computed property.
      watchers[key] = new Watcher(
        vm,
        getter || noop,
        noop,
        computedWatcherOptions
      )
    }

    // component-defined computed properties are already defined on the
    // component prototype. We only need to define computed properties defined
    // at instantiation here.
    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)
      }
    }
  }
}

defineComputed方法通过调用createComputedGetter方法包装了一下get方法,然后再用Object.defineProperty对当前计算属性进行数据劫持。

// https://github.com/vuejs/vue/blob/master/src/core/instance/state.js#L203
export function defineComputed (
  target: any,
  key: string,
  userDef: Object | Function
) {
  const shouldCache = !isServerRendering()
  if (typeof userDef === 'function') {
    sharedPropertyDefinition.get = shouldCache
      ? createComputedGetter(key)
      : userDef
    sharedPropertyDefinition.set = noop
  } else {
    sharedPropertyDefinition.get = userDef.get
      ? shouldCache && userDef.cache !== false
        ? createComputedGetter(key)
        : userDef.get
      : noop
    sharedPropertyDefinition.set = userDef.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)
}

下面我们来看看createComputedGetter是如何包装get方法的?

// https://github.com/vuejs/vue/blob/master/src/core/instance/state.js#L236
function createComputedGetter (key) {
  return function computedGetter () {
    // 取出在initComputed方法中的watcher实例
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      if (watcher.dirty) {
        // 执行watcher的回调,即computed属性的get方法, 把执行结果放在watcher.value
        watcher.evaluate()
      }
      // 收集依赖   
      if (Dep.target) {
        watcher.depend()
      }  
      return watcher.value
    }
  }
}

关于computed的代码就结束了,不过computed是如何实现缓存的,还是一头雾水。 其实关键代码在于上面提到的initComputed方法中的watcher实例。

通过watcher实现缓存

watcher的初始化,下面是初始化的主要代码。实例化参数:

// initComputed方法中的部分代码
const computedWatcherOptions = { lazy: true }

watchers[key] = new Watcher(
    vm,
    getter || noop, // computed属性的get方法, noop是空函数
    noop, // noop空函数
    computedWatcherOptions // 即 { lazy: true }
)
// https://github.com/vuejs/vue/blob/master/src/core/observer/watcher.js#L42
// 简略版的watcher
export default class Watcher {
    constructor(
        vm: Component,
        expOrFn: string | Function,
        cb: Function,
        options?: Object
    ) {
        this.vm = vm
        if (options) {
            // ... 
            this.lazy = !!options.lazy // true
        }
        this.cb = cb // 空函数
        this.dirty = this.lazy // true
        // ...
        this.getter = expOrFn // computed属性的get方法
        // 默认不会执行。
        // 当我们设置了computed属性,但是页面没有使用到的话,是不会触发computed的get方法
        this.value = this.lazy ? undefined : this.get()
    }
    get() {
        // 设置全局属性Dep.target,方便示例中的依赖属性firstName、lastName收集fullName的依赖
        pushTarget(this)
        let value
        const vm = this.vm
        // 触发computed的get方法, 完依赖收集。
        // 让fistName和lastName属性收集依赖,即computed属性的watcher
        value = this.getter.call(vm, vm)
        // 清除Dep.target属性
        popTarget()
        return value
    }
    // 触发依赖。
    // 在Dep的notify方法调用update
    // https://github.com/vuejs/vue/blob/master/src/core/observer/dep.js#L36
    update () {
        if (this.lazy) {
          this.dirty = true
        } 
        // ...
    }
    // computed包装的get方法会调用evaluate
    evaluate () {
        this.value = this.get()
        this.dirty = false
    }
}

至此,computed实现了缓存。

总结

回顾开头的问题,看看是否理解了computed的实现原理。

如何实现缓存?

  • 创建一个watcher实例,并传入lazy: true,包装computed的get方法computedGetter。
  • 页面template使用fullName,触发fullName的getter方法,即包装好的getter方法computedGetter
  • computedGetter方法中因为watcher.dirty为true,执行watcher.evaluate方法。
    • 在evaluate方法中,执行this.value = this.get(), 并把dirty设为false
    • 执行了get方法,即执行computedGetter方法,即执行computed的get方法,就会触发firstName和lastName的getter,从而把watcher收集进firstName和lastName的依赖中。
  • 重新获取computed属性的值,即触发getter方法时,因为dirty已经为false,就从watcher.value取缓存值。
  • 一旦firstName或者lastName发生变化,就会触发watcher.update方法,设置dirty为true。
  • 重新获取computed属性的值,就会执行watcher.evaluate方法,重新计算,并改变缓存值。

缓存值存在哪里?

watcher.value

rudyxu1102 avatar Nov 22 '20 11:11 rudyxu1102