Skip to content

Commit b3e61a4

Browse files
authored
fix(toRef): issue #855 (#859)
1 parent 15564dd commit b3e61a4

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

src/reactivity/ref.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { RefKey } from '../utils/symbols'
22
import { proxy, isPlainObject, warn, def } from '../utils'
33
import { reactive, isReactive, shallowReactive } from './reactive'
44
import { readonlySet } from '../utils/sets'
5+
import { set } from './set'
56

67
declare const _refBrand: unique symbol
78
export interface Ref<T = any> {
@@ -154,6 +155,7 @@ export function toRef<T extends object, K extends keyof T>(
154155
object: T,
155156
key: K
156157
): Ref<T[K]> {
158+
if (!(key in object)) set(object, key, undefined)
157159
const v = object[key]
158160
if (isRef<T[K]>(v)) return v
159161

test/apis/computed.spec.js

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,12 @@
11
const Vue = require('vue/dist/vue.common.js')
2-
const { ref, computed, isReadonly, reactive, isRef } = require('../../src')
2+
const {
3+
ref,
4+
computed,
5+
isReadonly,
6+
reactive,
7+
isRef,
8+
toRef,
9+
} = require('../../src')
310

411
describe('Hooks computed', () => {
512
beforeEach(() => {
@@ -195,6 +202,26 @@ describe('Hooks computed', () => {
195202
expect(app.$children[1].example).toBe('B')
196203
})
197204

205+
it('should watch a reactive property created via toRef', (done) => {
206+
const spy = jest.fn()
207+
const vm = new Vue({
208+
setup() {
209+
const a = reactive({})
210+
const b = toRef(a, 'b')
211+
212+
return {
213+
a,
214+
b,
215+
}
216+
},
217+
})
218+
vm.$watch('b', spy)
219+
vm.b = 2
220+
waitForUpdate(() => {
221+
expect(spy).toHaveBeenCalledWith(2, undefined)
222+
}).then(done)
223+
})
224+
198225
it('should be readonly', () => {
199226
let a = { a: 1 }
200227
const x = computed(() => a)

0 commit comments

Comments
 (0)