From 288b4eab9e10187eb14d4d6d54dc9f077343a2a5 Mon Sep 17 00:00:00 2001 From: Tan Li Hau Date: Tue, 21 Jul 2020 00:39:22 +0800 Subject: [PATCH] fix(watch): fix watching reactive array (#1656) fixes #1655 --- packages/runtime-core/__tests__/apiWatch.spec.ts | 10 ++++++++++ packages/runtime-core/src/apiWatch.ts | 12 ++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/runtime-core/__tests__/apiWatch.spec.ts b/packages/runtime-core/__tests__/apiWatch.spec.ts index 07b985c3c08..331b6f3c305 100644 --- a/packages/runtime-core/__tests__/apiWatch.spec.ts +++ b/packages/runtime-core/__tests__/apiWatch.spec.ts @@ -69,6 +69,16 @@ describe('api: watch', () => { expect(dummy).toMatchObject([1, 0]) }) + it('watching single source: array', async () => { + const array = reactive([] as number[]) + const spy = jest.fn() + watch(array, spy) + array.push(1) + await nextTick() + expect(spy).toBeCalledTimes(1) + expect(spy).toBeCalledWith([1], expect.anything(), expect.anything()) + }) + it('watching single source: computed ref', async () => { const count = ref(0) const plus = computed(() => count.value + 1) diff --git a/packages/runtime-core/src/apiWatch.ts b/packages/runtime-core/src/apiWatch.ts index fcc8c320308..de6f54e9e9b 100644 --- a/packages/runtime-core/src/apiWatch.ts +++ b/packages/runtime-core/src/apiWatch.ts @@ -159,7 +159,12 @@ function doWatch( } let getter: () => any - if (isArray(source)) { + if (isRef(source)) { + getter = () => source.value + } else if (isReactive(source)) { + getter = () => source + deep = true + } else if (isArray(source)) { getter = () => source.map(s => { if (isRef(s)) { @@ -172,11 +177,6 @@ function doWatch( __DEV__ && warnInvalidSource(s) } }) - } else if (isRef(source)) { - getter = () => source.value - } else if (isReactive(source)) { - getter = () => source - deep = true } else if (isFunction(source)) { if (cb) { // getter with cb