相关Vue版本 2.6.14
思考
我们都知道Vue computed的计算属性,会根据内部相关参数更新返回,那么下面代码中,如果num2更新了,computed会执行么???
<script setup>
import { ref, computed } from 'vue'
const num1 = ref(0);
const num2 = ref(1);
const flag = ref(true);
const comtd = computed(() => {
console.log('computed')
return flag.value ? num1.value : num2.value
})
</script>
<template>
<div @click="num1++">num1: {{ num1 }}</div>
<div @click="num2++">num2: {{ num2 }}</div>
<div @click="flag = !flag">flag: {{ flag }}</div>
<div>comtd: {{ comtd }}</div>
</template>
结果
结果如图
- 当
flag为true时,只有num1和flag的改变会执行对应的computed - 当
flag为false时,只有num2和flag会执行对应的computed
对应的
- 当
flag为true时,comtd的依赖dep中,仅包含flag和num1 - 当
flag为false时,comtd的依赖dep中,仅包含flag和num2
为什么呢?
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)
}
}
初始化流程中initState的时候,触发了initComputed
function initComputed (vm: Component, computed: Object) {
// $flow-disable-line
const watchers = vm._computedWatchers = Object.create(null)
const isSSR = isServerRendering()
for (const key in computed) {
const userDef = computed[key]
const getter = typeof userDef === 'function' ? userDef : userDef.get
...
if (!isSSR) {
// create internal watcher for the computed property.
watchers[key] = new Watcher(
vm,
getter || noop,
noop,
computedWatcherOptions
)
}
if (!(key in vm)) {
defineComputed(vm, key, userDef)
} else if (process.env.NODE_ENV !== 'production') {
...
}
}
}
initComputed省略了一下代码,保留了主流程,这里给每一个computed创建了一个watcher,然后继续执行defineComputed
export function defineComputed (
target: any,
key: string,
userDef: Object | Function
) {
...
sharedPropertyDefinition = createComputedGetter(key)
...
Object.defineProperty(target, key, sharedPropertyDefinition)
}
defineComputed省略了部分代码,保留主流程,这里使用到了Object.defineProperty,在对应的数据上绑定了createComputedGetter
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的字段getter时,会触发computedGetter,首次进入时,dirty为true,执行 watcher.evaluate,computed 计算完成之后,会在watcher.evaluate中设置 watcher.dirty = false
export default class Watcher {
...
et () {
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 {
// "touch" every property so they are all tracked as
// dependencies for deep watching
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
evaluate () {
this.value = this.get()
this.dirty = false
}
}
watcher.evaluate触发get方法,执行this.getter.call(vm, vm)
而就在此处,开始执行computed内部方法,每当执行到内部一个数据,会触发对应的Object.defineProperty 中的get方法
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
完成依赖收集(关键点)
在reactiveGetter中,会把当前get的数据depend到当前的watcher上,最终使得computed对应的watcher可以依赖到当前数据
下面是依赖收集完成后,当前computed对应的watcher数据结构
可以看到,watcher中的depIds依赖了7,9,分别是flag和num1对应的dep
并且每个dep中也会保存subs,代表那些数据依赖与它
可以看到上面Object.defineProperty的set中,会执行dep.notify()
就是这个时候去遍历dep的subs去执行watcher的update通知相关数据更新触发,
watcher.update中会修改watcher的watcher.dirty = true触发computed取消缓存,
此时computed并不会重新执行,而是需要当页面或者其他地方去get这个属性之后,才会执行computed