Skip to content

Commit bc167b5

Browse files
authoredOct 20, 2022
fix(runtime-core): watching multiple values - handle undefined as initial values (fix: #5032) (#5033)
1 parent 9617dd4 commit bc167b5

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed
 

‎packages/runtime-core/__tests__/apiWatch.spec.ts

+17
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,23 @@ describe('api: watch', () => {
177177
])
178178
})
179179

180+
it('watching multiple sources: undefined initial values and immediate: true', async () => {
181+
const a = ref()
182+
const b = ref()
183+
let called = false
184+
watch(
185+
[a, b],
186+
(newVal, oldVal) => {
187+
called = true
188+
expect(newVal).toMatchObject([undefined, undefined])
189+
expect(oldVal).toBeUndefined()
190+
},
191+
{ immediate: true }
192+
)
193+
await nextTick()
194+
expect(called).toBe(true)
195+
})
196+
180197
it('watching multiple sources: readonly array', async () => {
181198
const state = reactive({ count: 1 })
182199
const status = ref(false)

‎packages/runtime-core/src/apiWatch.ts

+7-2
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,9 @@ function doWatch(
296296
return NOOP
297297
}
298298

299-
let oldValue = isMultiSource ? [] : INITIAL_WATCHER_VALUE
299+
let oldValue: any = isMultiSource
300+
? new Array((source as []).length).fill(INITIAL_WATCHER_VALUE)
301+
: INITIAL_WATCHER_VALUE
300302
const job: SchedulerJob = () => {
301303
if (!effect.active) {
302304
return
@@ -323,7 +325,10 @@ function doWatch(
323325
callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
324326
newValue,
325327
// pass undefined as the old value when it's changed for the first time
326-
oldValue === INITIAL_WATCHER_VALUE ? undefined : oldValue,
328+
oldValue === INITIAL_WATCHER_VALUE ||
329+
(isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE)
330+
? undefined
331+
: oldValue,
327332
onCleanup
328333
])
329334
oldValue = newValue

0 commit comments

Comments
 (0)
Please sign in to comment.