computed怎么实现的缓存
参考答案
缓存的实现
class ComputedRefImpl {
constructor(getter) {
this._value = undefined
this._dirty = true // 脏标记
this.dep = new Dep()
this.effect = new ReactiveEffect(getter, () => {
if (!this._dirty) {
this._dirty = true // 上游变化只标脏,不立即重算
triggerRefValue(this) // 通知依赖此 computed 的 effect
}
})
}
get value() {
trackRefValue(this) // 收集依赖本 computed 的 effect
if (this._dirty) { // 只有脏了才重算
this._dirty = false
this._value = this.effect.run()
}
return this._value
}
}
三步
- 懒求值:不在创建时计算,第一次
get value才算; - 脏标记:上游依赖变化时,scheduler 只把
_dirty = true并通知下游,不立刻重算; - 缓存命中:再次访问时若
!_dirty,直接返回_value,不执行 getter。
Vue 2 的对应
function defineComputed(target, key, userDef) {
const getter = () => {
const watcher = this._computedWatchers[key]
if (watcher.dirty) {
watcher.evaluate() // 计算并把 dirty = false
}
if (Dep.target) watcher.depend() // 让依赖 computed 的 watcher 也订阅它的 dep
return watcher.value
}
Object.defineProperty(target, key, { get: getter, set: noop })
}
// Watcher with lazy: true → update() 里 if (this.lazy) this.dirty = true
同样是「dirty 标记 + lazy watcher + 依赖级联」。
关键点
- 不是每次访问都算,也不是每次都缓存——只在依赖变化后重算一次;
- 依赖变化不会让 computed 立刻重算(惰性),所以 computed 里不能做副作用;
- computed 的 dep 会把上层 effect(模板渲染、其他 computed、watch)挂上,形成级联;
- 手写
methods在模板里调用没有缓存,每次渲染都执行,这是「computed 比 methods 快」的原因; - Vue 3.4 之后 computed 的依赖追踪做了一些优化(减少不必要的重算),但机制仍是 dirty 缓存。