From bc167b5c6c7c5756f3b7720a7d3ddcdb2c7f717f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorsten=20L=C3=BCnborg?= Date: Thu, 20 Oct 2022 21:45:05 +0200 Subject: [PATCH] fix(runtime-core): watching multiple values - handle `undefined` as initial values (fix: #5032) (#5033) --- .../runtime-core/__tests__/apiWatch.spec.ts | 17 +++++++++++++++++ packages/runtime-core/src/apiWatch.ts | 9 +++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/packages/runtime-core/__tests__/apiWatch.spec.ts b/packages/runtime-core/__tests__/apiWatch.spec.ts index 86ad948adf6..c9db3657367 100644 --- a/packages/runtime-core/__tests__/apiWatch.spec.ts +++ b/packages/runtime-core/__tests__/apiWatch.spec.ts @@ -177,6 +177,23 @@ describe('api: watch', () => { ]) }) + it('watching multiple sources: undefined initial values and immediate: true', async () => { + const a = ref() + const b = ref() + let called = false + watch( + [a, b], + (newVal, oldVal) => { + called = true + expect(newVal).toMatchObject([undefined, undefined]) + expect(oldVal).toBeUndefined() + }, + { immediate: true } + ) + await nextTick() + expect(called).toBe(true) + }) + it('watching multiple sources: readonly array', async () => { const state = reactive({ count: 1 }) const status = ref(false) diff --git a/packages/runtime-core/src/apiWatch.ts b/packages/runtime-core/src/apiWatch.ts index 27215f342b3..19026cf645d 100644 --- a/packages/runtime-core/src/apiWatch.ts +++ b/packages/runtime-core/src/apiWatch.ts @@ -296,7 +296,9 @@ function doWatch( return NOOP } - let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE + let oldValue: any = isMultiSource + ? new Array((source as []).length).fill(INITIAL_WATCHER_VALUE) + : INITIAL_WATCHER_VALUE const job: SchedulerJob = () => { if (!effect.active) { return @@ -323,7 +325,10 @@ function doWatch( callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [ newValue, // pass undefined as the old value when it's changed for the first time - oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue, + oldValue === INITIAL_WATCHER_VALUE || + (isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE) + ? undefined + : oldValue, onCleanup ]) oldValue = newValue