Browse Source

fix: export proxyRefs

close #12600
Evan You 3 years ago
parent
commit
e452e9d436
3 changed files with 39 additions and 21 deletions
  1. 4 21
      src/v3/apiSetup.ts
  2. 1 0
      src/v3/index.ts
  3. 34 0
      src/v3/reactivity/ref.ts

+ 4 - 21
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<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 {

+ 1 - 0
src/v3/index.ts

@@ -7,6 +7,7 @@ export {
   toRef,
   toRefs,
   unref,
+  proxyRefs,
   customRef,
   triggerRef,
   Ref,

+ 34 - 0
src/v3/reactivity/ref.ts

@@ -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