From 0519e105189da6ba994d60da3107beca71e8745c Mon Sep 17 00:00:00 2001 From: Evan You Date: Tue, 20 Aug 2019 09:45:28 -0400 Subject: [PATCH] wip: make computed implementation consistent --- packages/reactivity/src/computed.ts | 16 ++++++++++++++-- packages/reactivity/src/index.ts | 2 +- packages/runtime-core/src/apiReactivity.ts | 14 ++------------ 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/packages/reactivity/src/computed.ts b/packages/reactivity/src/computed.ts index 5cbd1b5a..ef6e17c1 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 99112a94..71893f63 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 327cc385..fa67f54c 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 }