美文网首页
vue2中computed原理

vue2中computed原理

作者: web前端_潘哥哥 | 来源:发表于2021-09-01 16:21 被阅读0次

要理解这个,首先要理解vue2的数据响应式原理,因为computed这个API的实现是建立在数据响应式的基础之上的。
这里附上vue响应式原理的地址:vue2数据响应式原理

在vue的watcher实例中配置了lazy,dirty,value属性,就是用来配合实现computed的API。vue在初始化computed时,会给每一个computed属性配置一个watcher,并配置lazy的值为true。在new Watcher时,还会设置dirty为true。由于lazy为true,这个时候并不会执行computed配置的get方法,也就是说不会去计算出这个计算属性的值出来,那么什么时候才计算呢?就是在执行render函数时,会去取计算属性的值,这个时候,会执行计算属性的getter。在getter里面,会先判断dirty的值(为true,则表示当前计算属性的值为脏值,已经过期了,需要重新计算出来;为false则表示当前的值是最新的,不需要重新计算,直接取缓存里面的值就行了,也就是value字段的值)。如果为true,则调用watcher.evaluate方法计算最新的值出来,然后将dirty设为false,把最新的值赋值给value。在计算最新的值时,也就是执行我们在computed对象中配置的相应的get函数。根据之前讲的响应式原理,会先将当前的watcher挂到dep的静态属性target上,然后执行get,在这个过程中,会使用到data中的属性,然后进行依赖收集,将computed的watcher存到data数据对应的dep中去。完了之后,将watcher从targetStack中弹出,这是dep的静态属性target的值又变成了render函数的watcher。以上步骤执行完后,会判断当前dep的target是否还有值,有的话,会执行watcher.depend()。这一步是为了让依赖的data对应的dep中不仅是收集到computed的wathcer,还要收集render函数的watcher,因为当我们依赖的data改变时,不仅要通知到computed的watcher,还要通知render函数的watcher,达到重渲染的目的。然后会把最新的value值返回,这时,render函数里面终于拿到了计算属性的最新值了。假如后面继续用到了这个计算属性,那么在执行计算属性的getter时,跟之前一样,会先判断dirty值,这个时候,dirty的值为false,则直接返回value值,也就是之前说的取缓存的值,不会再次运行一遍计算属性的get函数了。
当某个时候,计算属性依赖的data数据变了,则会先后触发computed的watcher,还有render函数的watcher。在将vue的数据响应式原理时,我们知道,数据改变时,是会触发watcher的update方法。在这个方法里面,首先判断lazy是否为true,这就是针对计算属性设计的。我们可以看看源码片段:


vue2中watcher的update源码片段.png

如果为true,则只做了一件非常简单的事,就是把dirty设为了true,然后就没了。这个时候会去执行render函数的watcher.update。也就是把render函数的执行交给了nextTick去管理,这也是之前讲过的。在执行render函数时,又使用到了这个计算属性,那么,则会执行这个计算属性的getter,判断dirty是否为true,由于刚刚在执行computed的wathcer.update时,把dirty设为了true,这个时候肯定会执行watcher.evaluate重新去计算最新的值,也就是执行我们配置在computed里面的get函数。接下来的其实跟前面所讲的都是一样的了。

这里附上关于computed初始化的源码片段:

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 // {lazy: true}
      )
    }

    // 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)
      } else if (vm.$options.methods && key in vm.$options.methods) {
        warn(`The computed property "${key}" is already defined as a method.`, vm)
      }
    }
  }
}

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

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原理的理解了。

相关文章

网友评论

      本文标题:vue2中computed原理

      本文链接:https://www.haomeiwen.com/subject/lfgxwltx.html