Skip to content

Commit

Permalink
fix(toRef): issue #855 (#859)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rigo-m committed Nov 24, 2021
1 parent 15564dd commit b3e61a4
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
2 changes: 2 additions & 0 deletions src/reactivity/ref.ts
Expand Up @@ -2,6 +2,7 @@ import { RefKey } from '../utils/symbols'
import { proxy, isPlainObject, warn, def } from '../utils'
import { reactive, isReactive, shallowReactive } from './reactive'
import { readonlySet } from '../utils/sets'
import { set } from './set'

declare const _refBrand: unique symbol
export interface Ref<T = any> {
Expand Down Expand Up @@ -154,6 +155,7 @@ export function toRef<T extends object, K extends keyof T>(
object: T,
key: K
): Ref<T[K]> {
if (!(key in object)) set(object, key, undefined)
const v = object[key]
if (isRef<T[K]>(v)) return v

Expand Down
29 changes: 28 additions & 1 deletion test/apis/computed.spec.js
@@ -1,5 +1,12 @@
const Vue = require('vue/dist/vue.common.js')
const { ref, computed, isReadonly, reactive, isRef } = require('../../src')
const {
ref,
computed,
isReadonly,
reactive,
isRef,
toRef,
} = require('../../src')

describe('Hooks computed', () => {
beforeEach(() => {
Expand Down Expand Up @@ -195,6 +202,26 @@ describe('Hooks computed', () => {
expect(app.$children[1].example).toBe('B')
})

it('should watch a reactive property created via toRef', (done) => {
const spy = jest.fn()
const vm = new Vue({
setup() {
const a = reactive({})
const b = toRef(a, 'b')

return {
a,
b,
}
},
})
vm.$watch('b', spy)
vm.b = 2
waitForUpdate(() => {
expect(spy).toHaveBeenCalledWith(2, undefined)
}).then(done)
})

it('should be readonly', () => {
let a = { a: 1 }
const x = computed(() => a)
Expand Down

0 comments on commit b3e61a4

Please sign in to comment.