diff --git a/src/v3/apiSetup.ts b/src/v3/apiSetup.ts index 123f92113..e05735864 100644 --- a/src/v3/apiSetup.ts +++ b/src/v3/apiSetup.ts @@ -12,7 +12,7 @@ import { } from '../shared/util' import { currentInstance, setCurrentInstance } from './currentInstance' import { shallowReactive } from './reactivity/reactive' -import { isRef } from './reactivity/ref' +import { proxyWithRefUnwrap } from './reactivity/ref' /** * @internal @@ -68,7 +68,9 @@ export function initSetup(vm: Component) { // exposed for compiled render fn const proxy = (vm._setupProxy = {}) for (const key in setupResult) { - proxyWithRefUnwrap(proxy, setupResult, key) + if (key !== '__sfc') { + proxyWithRefUnwrap(proxy, setupResult, key) + } } } } else if (__DEV__ && setupResult !== undefined) { @@ -81,25 +83,6 @@ export function initSetup(vm: Component) { } } -export function proxyWithRefUnwrap( - target: any, - source: Record, - key: string -) { - Object.defineProperty(target, key, { - enumerable: true, - configurable: true, - get: () => { - const raw = source[key] - return isRef(raw) ? raw.value : raw - }, - set: newVal => { - const raw = source[key] - isRef(raw) ? (raw.value = newVal) : (source[key] = newVal) - } - }) -} - function createSetupContext(vm: Component): SetupContext { let exposeCalled = false return { diff --git a/src/v3/index.ts b/src/v3/index.ts index e2bec70e8..75c21ad32 100644 --- a/src/v3/index.ts +++ b/src/v3/index.ts @@ -7,6 +7,7 @@ export { toRef, toRefs, unref, + proxyRefs, customRef, triggerRef, Ref, diff --git a/src/v3/reactivity/ref.ts b/src/v3/reactivity/ref.ts index c61e29b1c..3b8d2fc7d 100644 --- a/src/v3/reactivity/ref.ts +++ b/src/v3/reactivity/ref.ts @@ -93,6 +93,40 @@ export function unref(ref: T | Ref): T { return isRef(ref) ? (ref.value as any) : ref } +export function proxyRefs( + objectWithRefs: T +): ShallowUnwrapRef { + if (isReactive(objectWithRefs)) { + return objectWithRefs as any + } + const proxy = {} + const keys = Object.keys(objectWithRefs) + for (let i = 0; i < keys.length; i++) { + proxyWithRefUnwrap(proxy, objectWithRefs, keys[i]) + } + return proxy as any +} + +export function proxyWithRefUnwrap( + target: any, + source: Record, + key: string +) { + Object.defineProperty(target, key, { + enumerable: true, + configurable: true, + get: () => unref(source[key]), + set: value => { + const oldValue = source[key] + if (isRef(oldValue) && !isRef(value)) { + oldValue.value = value + } else { + source[key] = value + } + } + }) +} + export type CustomRefFactory = ( track: () => void, trigger: () => void