diff --git a/packages/reactivity/src/computed.ts b/packages/reactivity/src/computed.ts index 5cbd1b5a2..ef6e17c13 100644 --- a/packages/reactivity/src/computed.ts +++ b/packages/reactivity/src/computed.ts @@ -1,17 +1,29 @@ import { effect, ReactiveEffect, activeReactiveEffectStack } from './effect' import { UnwrapNestedRefs, knownRefs } from './ref' +import { isFunction } from '@vue/shared' export interface ComputedRef { readonly value: UnwrapNestedRefs readonly effect: ReactiveEffect } +export interface ComputedOptions { + get: () => T + set: (v: T) => void +} + export function computed( - getter: () => T, - setter?: (v: T) => void + getterOrOptions: (() => T) | ComputedOptions ): ComputedRef { + const isReadonly = isFunction(getterOrOptions) + const getter = isReadonly + ? (getterOrOptions as (() => T)) + : (getterOrOptions as ComputedOptions).get + const setter = isReadonly ? null : (getterOrOptions as ComputedOptions).set + let dirty: boolean = true let value: any = undefined + const runner = effect(getter, { lazy: true, // mark effect as computed so that it gets priority during trigger diff --git a/packages/reactivity/src/index.ts b/packages/reactivity/src/index.ts index 99112a94c..71893f636 100644 --- a/packages/reactivity/src/index.ts +++ b/packages/reactivity/src/index.ts @@ -8,7 +8,7 @@ export { markImmutable, markNonReactive } from './reactive' -export { computed, ComputedRef } from './computed' +export { computed, ComputedRef, ComputedOptions } from './computed' export { effect, stop, diff --git a/packages/runtime-core/src/apiReactivity.ts b/packages/runtime-core/src/apiReactivity.ts index 327cc3852..fa67f54cb 100644 --- a/packages/runtime-core/src/apiReactivity.ts +++ b/packages/runtime-core/src/apiReactivity.ts @@ -23,11 +23,11 @@ export { import { computed as _computed, ComputedRef, + ComputedOptions, ReactiveEffect } from '@vue/reactivity' import { currentInstance } from './component' -import { isFunction } from '@vue/shared' // record effects created during a component's setup() so that they can be // stopped when the component unmounts @@ -37,20 +37,10 @@ export function recordEffect(effect: ReactiveEffect) { } } -interface ComputedOptions { - get: () => T - set: (v: T) => void -} - export function computed( getterOrOptions: (() => T) | ComputedOptions ): ComputedRef { - let c: ComputedRef - if (isFunction(getterOrOptions)) { - c = _computed(getterOrOptions) - } else { - c = _computed(getterOrOptions.get, getterOrOptions.set) - } + const c = _computed(getterOrOptions) recordEffect(c.effect) return c }