Skip to content

Commit

Permalink
feat(reactivity): add support for toRef API
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Apr 15, 2020
1 parent b83c580 commit 486dc18
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 2 deletions.
31 changes: 31 additions & 0 deletions packages/reactivity/__tests__/ref.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
effect,
reactive,
isRef,
toRef,
toRefs,
Ref,
isReactive
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -224,6 +253,8 @@ describe('reactivity/ref', () => {
}
}))

expect(isRef(custom)).toBe(true)

let dummy
effect(() => {
dummy = custom.value
Expand Down
1 change: 1 addition & 0 deletions packages/reactivity/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export {
unref,
shallowRef,
isRef,
toRef,
toRefs,
customRef,
Ref,
Expand Down
4 changes: 2 additions & 2 deletions packages/reactivity/src/ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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]> {
Expand Down
1 change: 1 addition & 0 deletions packages/runtime-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export {
unref,
shallowRef,
isRef,
toRef,
toRefs,
customRef,
reactive,
Expand Down

0 comments on commit 486dc18

Please sign in to comment.