From f4f0966b33863ac0fca6a20cf9e8ddfbb311ae87 Mon Sep 17 00:00:00 2001 From: Evan You Date: Sun, 16 Jan 2022 18:22:18 +0800 Subject: [PATCH] fix(ssr): make computed inactive during ssr, fix memory leak fix #5208 --- packages/reactivity/src/computed.ts | 11 +++++++---- packages/runtime-core/src/apiComputed.ts | 7 +++++++ packages/runtime-core/src/index.ts | 2 +- 3 files changed, 15 insertions(+), 5 deletions(-) create mode 100644 packages/runtime-core/src/apiComputed.ts diff --git a/packages/reactivity/src/computed.ts b/packages/reactivity/src/computed.ts index c7f7b051..c077d84b 100644 --- a/packages/reactivity/src/computed.ts +++ b/packages/reactivity/src/computed.ts @@ -36,7 +36,8 @@ class ComputedRefImpl { constructor( getter: ComputedGetter, private readonly _setter: ComputedSetter, - isReadonly: boolean + isReadonly: boolean, + isSSR: boolean ) { this.effect = new ReactiveEffect(getter, () => { if (!this._dirty) { @@ -44,6 +45,7 @@ class ComputedRefImpl { triggerRefValue(this) } }) + this.effect.active = !isSSR this[ReactiveFlags.IS_READONLY] = isReadonly } @@ -73,7 +75,8 @@ export function computed( ): WritableComputedRef export function computed( getterOrOptions: ComputedGetter | WritableComputedOptions, - debugOptions?: DebuggerOptions + debugOptions?: DebuggerOptions, + isSSR = false ) { let getter: ComputedGetter let setter: ComputedSetter @@ -91,9 +94,9 @@ export function computed( setter = getterOrOptions.set } - const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter) + const cRef = new ComputedRefImpl(getter, setter, onlyGetter || !setter, isSSR) - if (__DEV__ && debugOptions) { + if (__DEV__ && debugOptions && !isSSR) { cRef.effect.onTrack = debugOptions.onTrack cRef.effect.onTrigger = debugOptions.onTrigger } diff --git a/packages/runtime-core/src/apiComputed.ts b/packages/runtime-core/src/apiComputed.ts new file mode 100644 index 00000000..3804531b --- /dev/null +++ b/packages/runtime-core/src/apiComputed.ts @@ -0,0 +1,7 @@ +import { computed as _computed } from '@vue/reactivity' +import { isInSSRComponentSetup } from './component' + +export const computed = ((getterOrOptions: any, debugOptions?: any) => { + // @ts-ignore + return _computed(getterOrOptions, debugOptions, isInSSRComponentSetup) +}) as typeof _computed diff --git a/packages/runtime-core/src/index.ts b/packages/runtime-core/src/index.ts index 0d5e320e..65fc62b3 100644 --- a/packages/runtime-core/src/index.ts +++ b/packages/runtime-core/src/index.ts @@ -3,7 +3,6 @@ export const version = __VERSION__ export { // core - computed, reactive, ref, readonly, @@ -34,6 +33,7 @@ export { getCurrentScope, onScopeDispose } from '@vue/reactivity' +export { computed } from './apiComputed' export { watch, watchEffect,