fix(ssr): only cache computed getters during render phase

fix #5300
This commit is contained in:
Evan You
2022-01-21 12:31:54 +08:00
parent 25bc6549eb
commit 2f91872e7b
6 changed files with 75 additions and 9 deletions

View File

@@ -23,16 +23,18 @@ export interface WritableComputedOptions<T> {
set: ComputedSetter<T>
}
class ComputedRefImpl<T> {
export class ComputedRefImpl<T> {
public dep?: Dep = undefined
private _value!: T
private _dirty = true
public readonly effect: ReactiveEffect<T>
public readonly __v_isRef = true
public readonly [ReactiveFlags.IS_READONLY]: boolean
public _dirty = true
public _cacheable: boolean
constructor(
getter: ComputedGetter<T>,
private readonly _setter: ComputedSetter<T>,
@@ -45,7 +47,8 @@ class ComputedRefImpl<T> {
triggerRefValue(this)
}
})
this.effect.active = !isSSR
this.effect.computed = this
this.effect.active = this._cacheable = !isSSR
this[ReactiveFlags.IS_READONLY] = isReadonly
}
@@ -53,7 +56,7 @@ class ComputedRefImpl<T> {
// the computed ref may get wrapped by other proxies e.g. readonly() #3376
const self = toRaw(this)
trackRefValue(self)
if (self._dirty) {
if (self._dirty || !self._cacheable) {
self._dirty = false
self._value = self.effect.run()!
}

View File

@@ -58,14 +58,14 @@ class DeferredComputedRefImpl<T> {
// value invalidation in case of sync access; normal effects are
// deferred to be triggered in scheduler.
for (const e of this.dep) {
if (e.computed) {
if (e.computed instanceof DeferredComputedRefImpl) {
e.scheduler!(true /* computedTrigger */)
}
}
}
this._dirty = true
})
this.effect.computed = true
this.effect.computed = this as any
}
private _get() {

View File

@@ -9,6 +9,7 @@ import {
newTracked,
wasTracked
} from './dep'
import { ComputedRefImpl } from './computed'
// The main WeakMap that stores {target -> key -> dep} connections.
// Conceptually, it's easier to think of a dependency as a Dep class
@@ -54,9 +55,16 @@ export class ReactiveEffect<T = any> {
active = true
deps: Dep[] = []
// can be attached after creation
computed?: boolean
/**
* Can be attached after creation
* @internal
*/
computed?: ComputedRefImpl<T>
/**
* @internal
*/
allowRecurse?: boolean
onStop?: () => void
// dev only
onTrack?: (event: DebuggerEvent) => void