feat(reactivity): add support for toRef API

This commit is contained in:
Evan You 2020-04-14 20:49:18 -04:00
parent b83c580131
commit 486dc188fe
4 changed files with 35 additions and 2 deletions

View File

@ -3,6 +3,7 @@ import {
effect, effect,
reactive, reactive,
isRef, isRef,
toRef,
toRefs, toRefs,
Ref, Ref,
isReactive isReactive
@ -168,6 +169,34 @@ describe('reactivity/ref', () => {
expect(isRef({ value: 0 })).toBe(false) 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', () => { test('toRefs', () => {
const a = reactive({ const a = reactive({
x: 1, x: 1,
@ -224,6 +253,8 @@ describe('reactivity/ref', () => {
} }
})) }))
expect(isRef(custom)).toBe(true)
let dummy let dummy
effect(() => { effect(() => {
dummy = custom.value dummy = custom.value

View File

@ -3,6 +3,7 @@ export {
unref, unref,
shallowRef, shallowRef,
isRef, isRef,
toRef,
toRefs, toRefs,
customRef, customRef,
Ref, Ref,

View File

@ -103,12 +103,12 @@ export function toRefs<T extends object>(
} }
const ret: any = {} const ret: any = {}
for (const key in object) { for (const key in object) {
ret[key] = toProxyRef(object, key) ret[key] = toRef(object, key)
} }
return ret return ret
} }
function toProxyRef<T extends object, K extends keyof T>( export function toRef<T extends object, K extends keyof T>(
object: T, object: T,
key: K key: K
): Ref<T[K]> { ): Ref<T[K]> {

View File

@ -6,6 +6,7 @@ export {
unref, unref,
shallowRef, shallowRef,
isRef, isRef,
toRef,
toRefs, toRefs,
customRef, customRef,
reactive, reactive,