]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(reactivity): add support for `toRef` API
authorEvan You <yyx990803@gmail.com>
Wed, 15 Apr 2020 00:49:18 +0000 (20:49 -0400)
committerEvan You <yyx990803@gmail.com>
Wed, 15 Apr 2020 00:49:18 +0000 (20:49 -0400)
packages/reactivity/__tests__/ref.spec.ts
packages/reactivity/src/index.ts
packages/reactivity/src/ref.ts
packages/runtime-core/src/index.ts

index 9ebe8f46ea69f2bea9dc65a53190b90582c871c6..27c7a0b260d61126dd427fe094f3b4cfc8e12be2 100644 (file)
@@ -3,6 +3,7 @@ import {
   effect,
   reactive,
   isRef,
+  toRef,
   toRefs,
   Ref,
   isReactive
@@ -168,6 +169,34 @@ describe('reactivity/ref', () => {
     expect(isRef({ value: 0 })).toBe(false)
   })
 
+  test('toRef', () => {
+    const a = reactive({
+      x: 1
+    })
+    const x = toRef(a, 'x')
+    expect(isRef(x)).toBe(true)
+    expect(x.value).toBe(1)
+
+    // source -> proxy
+    a.x = 2
+    expect(x.value).toBe(2)
+
+    // proxy -> source
+    x.value = 3
+    expect(a.x).toBe(3)
+
+    // reactivity
+    let dummyX
+    effect(() => {
+      dummyX = x.value
+    })
+    expect(dummyX).toBe(x.value)
+
+    // mutating source should trigger effect using the proxy refs
+    a.x = 4
+    expect(dummyX).toBe(4)
+  })
+
   test('toRefs', () => {
     const a = reactive({
       x: 1,
@@ -224,6 +253,8 @@ describe('reactivity/ref', () => {
       }
     }))
 
+    expect(isRef(custom)).toBe(true)
+
     let dummy
     effect(() => {
       dummy = custom.value
index d83b0f305853d37344728b212fa6a8d1556783ea..0a173731736346fc16d8e3ff4711a0f4621b4ede 100644 (file)
@@ -3,6 +3,7 @@ export {
   unref,
   shallowRef,
   isRef,
+  toRef,
   toRefs,
   customRef,
   Ref,
index bbbd94841a344ea8de182dfd73cd380669559cc3..8338ffab22652df86acc5f09c12dad84953d79a7 100644 (file)
@@ -103,12 +103,12 @@ export function toRefs<T extends object>(
   }
   const ret: any = {}
   for (const key in object) {
-    ret[key] = toProxyRef(object, key)
+    ret[key] = toRef(object, key)
   }
   return ret
 }
 
-function toProxyRef<T extends object, K extends keyof T>(
+export function toRef<T extends object, K extends keyof T>(
   object: T,
   key: K
 ): Ref<T[K]> {
index 2b4923e2323d4a978474728984d805ba31dc9c05..c1cf0c5d1e44e3b197f24ecc5f6a230574d7c06c 100644 (file)
@@ -6,6 +6,7 @@ export {
   unref,
   shallowRef,
   isRef,
+  toRef,
   toRefs,
   customRef,
   reactive,