feat(computed): 实现计算属性缓存优化和调度器支持

- 添加 _dirty 标志位控制计算属性重新执行逻辑
- 在 ReactiveEffect 构造函数中增加调度器参数支持
- 实现计算属性值变更时的依赖触发机制
- 重构 triggerEffects 函数优先处理计算属性依赖
- 新增 EffectScheduler 类型定义统一调度器类型
- 添加 computed-cache.html 示例验证缓存功能
This commit is contained in:
dj
2026-02-08 22:39:34 +08:00
parent 4c60486511
commit c07431db08
3 changed files with 67 additions and 9 deletions

View File

@@ -1,20 +1,30 @@
import { isFunction } from '@vue/shared'
import { Dep } from './dep'
import { ReactiveEffect } from './effect'
import { trackRefValue } from './ref'
import { trackRefValue, triggerRefValue } from './ref'
export class ComputedRefImpl<T> {
public dep?: Dep = undefined
private _value!: T
public readonly effect: ReactiveEffect<T>
public readonly __v_isRef = true
public _dirty = true //为true时,需要重新执行run方法, 也就是说数据脏了的意思
constructor(getter) {
this.effect = new ReactiveEffect(getter)
this.effect = new ReactiveEffect(getter, () => {
if (!this._dirty) {
this._dirty = true
triggerRefValue(this)
}
})
this.effect.computed = this
}
get value() {
trackRefValue(this) //触发依赖
this._value = this.effect.run()
trackRefValue(this)
if (this._dirty) {
this._dirty = false
this._value = this.effect.run()
}
return this._value
}
}

View File

@@ -1,6 +1,7 @@
import { createDep, Dep } from './dep'
import { isArray } from '@vue/shared'
import { ComputedRefImpl } from './computed'
export type EffectScheduler = (...args: any[]) => any
type KeyToDepMap = Map<any, Dep>
/**
@@ -21,7 +22,10 @@ export let activeEffect: ReactiveEffect | undefined
export class ReactiveEffect<T = any> {
computed?: ComputedRefImpl<T>
constructor(public fn: () => T) {}
constructor(
public fn: () => T,
public scheduler: EffectScheduler | null = null
) {}
run() {
//当前被激活的effect实例
activeEffect = this
@@ -78,14 +82,26 @@ export function trigger(target: object, key: unknown, newValue: unknown) {
}
/**
* 依次触发dep中保存的依赖
* 触发dep中保存的依赖
* @param dep
*/
export function triggerEffects(dep: Dep) {
//把dep构建为一个数组
const effects = isArray(dep) ? dep : [...dep]
//依次触发依赖
//不再依次触发依赖
// for (const effect of effects) {
// triggerEffect(effect)
// }
//而是先触发所有的计算属性依赖, 再触发所有的非计算属性依赖
for (const effect of effects) {
triggerEffect(effect)
if (effect.computed) {
triggerEffect(effect)
}
}
for (const effect of effects) {
if (!effect.computed) {
triggerEffect(effect)
}
}
}
@@ -94,5 +110,9 @@ export function triggerEffects(dep: Dep) {
* @param effect
*/
export function triggerEffect(effect: ReactiveEffect) {
effect.run()
if (effect.scheduler) {
effect.scheduler()
} else {
effect.run()
}
}