mirror of
https://github.com/vuejs/vue.git
synced 2024-11-21 20:28:54 +00:00
parent
bcb62d1a00
commit
e452e9d436
@ -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,9 +68,11 @@ export function initSetup(vm: Component) {
|
||||
// exposed for compiled render fn
|
||||
const proxy = (vm._setupProxy = {})
|
||||
for (const key in setupResult) {
|
||||
if (key !== '__sfc') {
|
||||
proxyWithRefUnwrap(proxy, setupResult, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (__DEV__ && setupResult !== undefined) {
|
||||
warn(
|
||||
`setup() should return an object. Received: ${
|
||||
@ -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 {
|
||||
|
@ -7,6 +7,7 @@ export {
|
||||
toRef,
|
||||
toRefs,
|
||||
unref,
|
||||
proxyRefs,
|
||||
customRef,
|
||||
triggerRef,
|
||||
Ref,
|
||||
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user