vue源码分析(十二)核心函数之initComputed

2020-04-21  本文已影响0人  vue爱好者

我们打开文件 src/core/instance/state.js,找到定义initComputed函数的代码:

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变量并且赋值了一个空对象,同时给 vm对象挂载了 _computedWatchers属性。
const watchers = vm._computedWatchers = Object.create(null)

接下来判断了如果不是ssr环境,就给key添加一个Watcher监听。
如果key不存在vm对象上面,就对key进行Object.defineProperty监听,否则就是计算属性的key不能和data以及prop相同。

上一篇 下一篇

猜你喜欢

热点阅读