Skip to content

Commit 4acbf09

Browse files
committed
fix(runtime-core): when using the deep mode of watch, watchCallBack will be triggered even if the value does not change (fix vuejs#7160)
1 parent f3e4f03 commit 4acbf09

File tree

2 files changed

+30
-8
lines changed

2 files changed

+30
-8
lines changed

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1150,4 +1150,26 @@ describe('api: watch', () => {
11501150
// own update effect
11511151
expect(instance!.scope.effects.length).toBe(1)
11521152
})
1153+
1154+
// #7160
1155+
test('when using the deep mode of watch, watchCallBack wont be triggered if the value does not change', async () => {
1156+
const msg = ref('hi')
1157+
const msgTrim = computed(() => msg.value.trim())
1158+
1159+
let changeCounter = 0
1160+
let deepChangeCounter = 0
1161+
1162+
watch(msgTrim, () => ++changeCounter)
1163+
watch(msgTrim, () => ++deepChangeCounter, { deep: true })
1164+
1165+
msg.value = 'hi!'
1166+
await nextTick()
1167+
expect(changeCounter).toBe(1)
1168+
expect(deepChangeCounter).toBe(1)
1169+
1170+
msg.value = 'hi! '
1171+
await nextTick()
1172+
expect(changeCounter).toBe(1)
1173+
expect(deepChangeCounter).toBe(1)
1174+
})
11531175
})

packages/runtime-core/src/apiWatch.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -311,13 +311,13 @@ function doWatch(
311311
// watch(source, cb)
312312
const newValue = effect.run()
313313
if (
314-
deep ||
315314
forceTrigger ||
316315
(isMultiSource
317-
? (newValue as any[]).some((v, i) =>
318-
hasChanged(v, (oldValue as any[])[i])
316+
? (newValue as any[]).some(
317+
(v, i) =>
318+
(deep && isObject(v)) || hasChanged(v, (oldValue as any[])[i])
319319
)
320-
: hasChanged(newValue, oldValue)) ||
320+
: (deep && isObject(newValue)) || hasChanged(newValue, oldValue)) ||
321321
(__COMPAT__ &&
322322
isArray(newValue) &&
323323
isCompatEnabled(DeprecationTypes.WATCH_ARRAY, instance))
@@ -329,11 +329,11 @@ function doWatch(
329329
callWithAsyncErrorHandling(cb, instance, ErrorCodes.WATCH_CALLBACK, [
330330
newValue,
331331
// pass undefined as the old value when it's changed for the first time
332-
oldValue === INITIAL_WATCHER_VALUE
332+
oldValue === INITIAL_WATCHER_VALUE
333333
? undefined
334-
: (isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE)
335-
? []
336-
: oldValue,
334+
: isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE
335+
? []
336+
: oldValue,
337337
onCleanup
338338
])
339339
oldValue = newValue

0 commit comments

Comments
 (0)