Vue源码分析——computed

2018-02-27

看这篇文之前最好先看写的observer分析方便更好的理解

直接上源码version: 2.5.13, 初始化computed

// core/instance/state.js
const computedWatcherOptions = { lazy: true }

function initComputed (vm: Component, computed: Object) {
  // $flow-disable-line
  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)
      }
    }
  }
}

创建watchers来存储watcher实例,遍历computed对象,来对每个key进行处理
const userDef = computed[key]知道userDef就是我们所写的function, 一般情况下getter就是userDef
举个简单的例子,我们平时是这样写的

export default {
  data(){
    return {
      bar: 12
    }
  },
  computed: {
    foo() {
      return this.bar / 2
    }
  }
}

所以key就是foo字段,而userDefgetter就是foo函数
每个key都会创建一个懒惰的watcher实例,按之前分析observer所讲的,watcher会根据getter来收集依赖, 但懒惰的watcher不会先收集依赖。
上面这段代码就订阅了bar这个属性。当this.bar修改的时候,就是通知这个watcher, 最后执行getter

但我们this.foo的时候怎么获取到这个属性呢,这又用到了Object.defineProperty
往下看,可以看到if (!(key in vm)),这段就是判断data是否已经存在了这个key,是否与datakey冲突。
我们看下defineComputed(vm, key, userDef)的实现

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

很快可以看出就是重新定义了key的属性,
如果是服务端渲染,它的getteruserDef函数;
如果不是,则它的getter就是createComputedGetter(key)

我们一般做的都不是服务端渲染,所以我们来看下createComputedGetter干了什么

function createComputedGetter (key) {
  return function computedGetter () {
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      if (watcher.dirty) {
        // 获取watcher.value
        watcher.evaluate()
      }
      if (Dep.target) {
        // 依赖收集
        watcher.depend()
      }
      return watcher.value
    }
  }
}

返回了一个函数作为属性的getter,而上面说的computed创建的watcher实例都是懒惰的。
所以第一次获取值的时候,我们要watcher.evaluate(), 收集依赖,并获取watcher.value的值,最后返回watcher.value
我们用this.foo获取的是watcher.value, 而wathcer.value其实就是getter方法的结果,而getter就是我们的foo函数
我们可以看下watcher.js, 只显示了主要代码

// watcher.js
export default class Watcher {
  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    // parse expression for getter
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } 
    this.value = this.lazy
      ? undefined
      : this.get()
  }
  get () {
    // Dep.target赋值为当前实例
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      value = this.getter.call(vm, vm)
    } catch (e) {
      if (this.user) {
        handleError(e, vm, `getter for watcher "${this.expression}"`)
      } else {
        throw e
      }
    } finally {
      if (this.deep) {
        traverse(value)
      }
      popTarget()
      this.cleanupDeps()
    }
    return value
  },
  evaluate () {
    this.value = this.get()
    this.dirty = false
  }
}

总结下:
因此我们在获取初始化computed的时候,每个key创建一个懒惰(lazy)的watcher实例。懒惰的也就是不先收集依赖。
之后用Object.defineProperty在vm上重新定义key的属性, 这样我们可以直接用this[key]来使用
如果是服务端渲染,属性的getter就是我们写的function
如果不是服务端渲染,getter返回的是watcher.value
因为是懒惰的,第一次获取this[key]才会收集依赖。
因为当依赖改变的时候,会通知watcher去改变watcher.value,也就实现了computed
所以当依赖不改变。计算属性是不会改变的