From 620d09b1df794250a114eb71e156841971b9038f Mon Sep 17 00:00:00 2001 From: Yunfei He Date: Sat, 5 Jun 2021 06:34:12 +0800 Subject: [PATCH] fix(shallowReactive): should keep array as array (#717) --- src/reactivity/reactive.ts | 2 +- test/v3/reactivity/reactive.spec.ts | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/reactivity/reactive.ts b/src/reactivity/reactive.ts index 37779587..4cc72803 100644 --- a/src/reactivity/reactive.ts +++ b/src/reactivity/reactive.ts @@ -156,7 +156,7 @@ export function shallowReactive(obj: any): any { return obj as any } - const observed = observe({}) + const observed = observe(isArray(obj) ? [] : {}) setupAccessControl(observed) const ob = (observed as any).__ob__ diff --git a/test/v3/reactivity/reactive.spec.ts b/test/v3/reactivity/reactive.spec.ts index 75f9e824..4ae2e7de 100644 --- a/test/v3/reactivity/reactive.spec.ts +++ b/test/v3/reactivity/reactive.spec.ts @@ -206,6 +206,24 @@ describe('reactivity/reactive', () => { props.n = reactive({ foo: 2 }) expect(isReactive(props.n)).toBe(true) }) + + test('should keep array as array', () => { + const arr = [1, 2, 3] + const shallowReactiveArr = shallowReactive(arr) + expect(Array.isArray(shallowReactiveArr)).toBe(true) + expect(shallowReactiveArr.join(' ')).toBe(arr.join(' ')) + }) + + test('should trigger computed when changed', () => { + const arr = Array(10).fill(0) + const shallowReactiveArr = shallowReactive(arr) + const sum = computed(() => + shallowReactiveArr.reduce((acc, cur) => acc + cur, 0) + ) + expect(sum.value).toBe(0) + shallowReactiveArr[0] = 1 + expect(sum.value).toBe(1) + }) }) test('should shallowReactive non-observable values', () => {