Vue Computed 依赖收集与更新原理

今天面了家小公司,上来直接问 computed 底层原理,面试官是这样问的,data 中定义了 a 和 b 变量。computed 里面定义了 c 属性,c 的结果依赖与 a 和 b,模板中使用了变量 c。假设改变了 a,请问底层是如何收集依赖,如何触发更新的?

<div>{{ c }}</div>
data(){
	return {
		a: 'foo',
		b: 'bar'
	}
},
computed: {
	c() { 
		return this.a + ' - ' + this.b;
	 }
},
mounted(){
	setTimeout(() => { this.a = 'FOO' }, 1000)
}

页面效果:先显示了 foo - bar,一秒之后显示 FOO - bar

这里查源码后,对 computed 原理简述如下:

  1. initState 函数中初始化了 initComputed
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)
  }
}
  1. initComputed 函数中遍历 computed 中每一个属性,并且 new Watcher(computed watcher),可以看到传入 Watcher 构造函数的 cb 是 noop,它是一个空函数。并且 defineComputed
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)
      } else if (vm.$options.methods && key in vm.$options.methods) {
        warn(`The computed property "${key}" is already defined as a method.`, vm)
      }
    }
  }
}
  1. defineComputed 中使用了 Object.defineProperty 对属性进行劫持,获取是返回对应的 getter 即 createComputedGetter
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
    }
  }
}

看到这里,我们大致可以理解,Vue 组件在初始化时,initState -> initComputed -> new Watcher() 计算watcher,传入的 callback 是 computer 属性的 getter,由于 computed 是 lazy: true watcher,所以 new Watcher 时并不会立即执行 watcher 实例上的 get(), 而是在 defineComputed 函数里面调用 createComputedGetter 函数,在 createComputedGetter 函数执行了 watcher.evaluate() 进而执行了 watcher.get().

执行 watcher.get() 首先 pushTarget(this),将 Dep.target 赋值为当前的 computed watcher,然后执行 this.getter
也就是执行 computer 属性配置的 getter,执行getter 就会访问所依赖的每一个值,就会被 Object.defineProperty 劫持到进入 get ,执行 dep.depend() , 会为每一个属性对应的 dep 实例添加一个 computed watcher,同时这个 computed watcher 也会保存对应的 dep。

说了这么多都在讲 computed watcher,那修改 this.a 页面为什么会发生更新呢?

答案:因为 this.a 的依赖中不仅有 computed watcher 还有一个 render watcher

原因:

$mount 是会执行 mountComponent,会创建一个 render watcher,它会立即执行 cb(目前 Dep.target 是 render watcher),调用 render 函数在底层编译模板,最后访问属性计算属性 c,访问计算属性 c 就必定会访问 a,当访问 a 时会触发 defineComputed 中的 Object.defineProperty 进而劫持调用 createComputedGetter,进而调用 watcher.depend(),这个 watcher 是 computed watcher

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
    }
  }
}
// Watcher.js
depend () {
  let i = this.deps.length
  while (i--) {
    this.deps[i].depend()
  }
}

调用 watcher.depend() , this 指的是 computed watcher,会将 computed watcher 里面的 deps 保存在所有依赖调用 deps[i].depend(),进而调用 Dep 类中的 Dep.target.addDep(this),使得 render watcher 中保存了当前的 dep,dep 中同时保存了 render watcher

dep 中同时保存了 render watcher。就可以看出,示例中的属性 a 的 dep 中也会保存 render watcher,所以 a 属性的 dep 中有两个 watcher: [computedWatcher, renderWatcher]

所以,修改 a 属性的值,最后 notify 会清空这个 保存 watcher 的队列,进行页面更新!Okay!

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
vue中的computed原理是通过定义计算属性来实现对数据的处理和监听。计算属性是一种根据已有数据计算得出的属性,它会根据依赖的数据进行自动更新。在vue中,我们可以通过computed属性来定义计算属性。 computed属性是一个对象,其中的每一个属性对应一个计算属性。在计算属性中,我们可以编写一个函数,该函数返回的值就是计算属性的最终值。计算属性会自动根据它所依赖的数据进行缓存,只有依赖的数据发生变化时,才会重新计算。 当计算属性所依赖的数据发生变化时,computed会自动触发重新计算,并将计算结果缓存起来。这样,当其他地方需要使用计算属性时,直接获取缓存的值,不需要每次都重新计算,从而提高了性能。 一个计算属性可以依赖多个数据,当其中任意一个数据变化时,计算属性会重新计算。Vue会建立计算属性与数据之间的依赖关系,并在依赖的数据发生变化时,自动通知计算属性进行重新计算。 通过computed属性,我们可以将一些复杂的数据处理逻辑封装成函数,让代码更加清晰和易读。另外,在模板中使用计算属性的值时,直接通过计算属性的名称引用即可,不需要手动调用函数。 综上所述,computed原理是通过定义计算属性实现对数据的处理和监听,它会自动根据依赖的数据进行缓存和更新。这样可以提高性能,并使数据处理的逻辑更加清晰和易读。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值