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

View File

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

View 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]> {

View File

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