Skip to content

Commit 4172fdb

Browse files
feat(reactivity): return array when calling toRefs on array (#1768)
close #1764
1 parent fdb2f41 commit 4172fdb

File tree

2 files changed

+24
-7
lines changed

2 files changed

+24
-7
lines changed

packages/reactivity/__tests__/ref.spec.ts

+22-5
Original file line numberDiff line numberDiff line change
@@ -266,12 +266,29 @@ describe('reactivity/ref', () => {
266266
expect(dummyY).toBe(5)
267267
})
268268

269-
test('toRefs pass a reactivity object', () => {
270-
console.warn = jest.fn()
271-
const obj = { x: 1 }
272-
toRefs(obj)
273-
expect(console.warn).toBeCalled()
269+
test('toRefs should warn on plain object', () => {
270+
toRefs({})
271+
expect(`toRefs() expects a reactive object`).toHaveBeenWarned()
274272
})
273+
274+
test('toRefs should warn on plain array', () => {
275+
toRefs([])
276+
expect(`toRefs() expects a reactive object`).toHaveBeenWarned()
277+
})
278+
279+
test('toRefs reactive array', () => {
280+
const arr = reactive(['a', 'b', 'c'])
281+
const refs = toRefs(arr)
282+
283+
expect(Array.isArray(refs)).toBe(true)
284+
285+
refs[0].value = '1'
286+
expect(arr[0]).toBe('1')
287+
288+
arr[1] = '2'
289+
expect(refs[1].value).toBe('2')
290+
})
291+
275292
test('customRef', () => {
276293
let value = 1
277294
let _trigger: () => void

packages/reactivity/src/ref.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { track, trigger } from './effect'
22
import { TrackOpTypes, TriggerOpTypes } from './operations'
3-
import { isObject, hasChanged } from '@vue/shared'
3+
import { isArray, isObject, hasChanged } from '@vue/shared'
44
import { reactive, isProxy, toRaw, isReactive } from './reactive'
55
import { CollectionTypes } from './collectionHandlers'
66

@@ -121,7 +121,7 @@ export function toRefs<T extends object>(object: T): ToRefs<T> {
121121
if (__DEV__ && !isProxy(object)) {
122122
console.warn(`toRefs() expects a reactive object but received a plain one.`)
123123
}
124-
const ret: any = {}
124+
const ret: any = isArray(object) ? new Array(object.length) : {}
125125
for (const key in object) {
126126
ret[key] = toRef(object, key)
127127
}

0 commit comments

Comments
 (0)