Skip to content

Commit 620d09b

Browse files
authored
fix(shallowReactive): should keep array as array (#717)
1 parent f08a1d6 commit 620d09b

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/reactivity/reactive.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ export function shallowReactive(obj: any): any {
156156
return obj as any
157157
}
158158

159-
const observed = observe({})
159+
const observed = observe(isArray(obj) ? [] : {})
160160
setupAccessControl(observed)
161161

162162
const ob = (observed as any).__ob__

test/v3/reactivity/reactive.spec.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,24 @@ describe('reactivity/reactive', () => {
206206
props.n = reactive({ foo: 2 })
207207
expect(isReactive(props.n)).toBe(true)
208208
})
209+
210+
test('should keep array as array', () => {
211+
const arr = [1, 2, 3]
212+
const shallowReactiveArr = shallowReactive(arr)
213+
expect(Array.isArray(shallowReactiveArr)).toBe(true)
214+
expect(shallowReactiveArr.join(' ')).toBe(arr.join(' '))
215+
})
216+
217+
test('should trigger computed when changed', () => {
218+
const arr = Array(10).fill(0)
219+
const shallowReactiveArr = shallowReactive(arr)
220+
const sum = computed(() =>
221+
shallowReactiveArr.reduce((acc, cur) => acc + cur, 0)
222+
)
223+
expect(sum.value).toBe(0)
224+
shallowReactiveArr[0] = 1
225+
expect(sum.value).toBe(1)
226+
})
209227
})
210228

211229
test('should shallowReactive non-observable values', () => {

0 commit comments

Comments
 (0)