Skip to content

Commit

Permalink
fix: export proxyRefs
Browse files Browse the repository at this point in the history
close #12600
  • Loading branch information
yyx990803 committed Jul 4, 2022
1 parent bcb62d1 commit e452e9d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 21 deletions.
25 changes: 4 additions & 21 deletions src/v3/apiSetup.ts
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand All @@ -81,25 +83,6 @@ export function initSetup(vm: Component) {
}
}

export function proxyWithRefUnwrap(
target: any,
source: Record<string, any>,
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 {
Expand Down
1 change: 1 addition & 0 deletions src/v3/index.ts
Expand Up @@ -7,6 +7,7 @@ export {
toRef,
toRefs,
unref,
proxyRefs,
customRef,
triggerRef,
Ref,
Expand Down
34 changes: 34 additions & 0 deletions src/v3/reactivity/ref.ts
Expand Up @@ -93,6 +93,40 @@ export function unref<T>(ref: T | Ref<T>): T {
return isRef(ref) ? (ref.value as any) : ref
}

export function proxyRefs<T extends object>(
objectWithRefs: T
): ShallowUnwrapRef<T> {
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<string, any>,
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<T> = (
track: () => void,
trigger: () => void
Expand Down

0 comments on commit e452e9d

Please sign in to comment.