Skip to content

Commit

Permalink
fix(runtime-core): when using the deep mode of watch, watchCallBack w…
Browse files Browse the repository at this point in the history
…ill be triggered even if the value does not change (fix vuejs#7160)
  • Loading branch information
LittleSound committed Nov 17, 2022
1 parent f3e4f03 commit 4acbf09
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
22 changes: 22 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1150,4 +1150,26 @@ describe('api: watch', () => {
// own update effect
expect(instance!.scope.effects.length).toBe(1)
})

// #7160
test('when using the deep mode of watch, watchCallBack wont be triggered if the value does not change', async () => {
const msg = ref('hi')
const msgTrim = computed(() => msg.value.trim())

let changeCounter = 0
let deepChangeCounter = 0

watch(msgTrim, () => ++changeCounter)
watch(msgTrim, () => ++deepChangeCounter, { deep: true })

msg.value = 'hi!'
await nextTick()
expect(changeCounter).toBe(1)
expect(deepChangeCounter).toBe(1)

msg.value = 'hi! '
await nextTick()
expect(changeCounter).toBe(1)
expect(deepChangeCounter).toBe(1)
})
})
16 changes: 8 additions & 8 deletions packages/runtime-core/src/apiWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -311,13 +311,13 @@ function doWatch(
// watch(source, cb)
const newValue = effect.run()
if (
deep ||
forceTrigger ||
(isMultiSource
? (newValue as any[]).some((v, i) =>
hasChanged(v, (oldValue as any[])[i])
? (newValue as any[]).some(
(v, i) =>
(deep && isObject(v)) || hasChanged(v, (oldValue as any[])[i])
)
: hasChanged(newValue, oldValue)) ||
: (deep && isObject(newValue)) || hasChanged(newValue, oldValue)) ||
(__COMPAT__ &&
isArray(newValue) &&
isCompatEnabled(DeprecationTypes.WATCH_ARRAY, instance))
Expand All @@ -329,11 +329,11 @@ 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
oldValue === INITIAL_WATCHER_VALUE
? undefined
: (isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE)
? []
: oldValue,
: isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE
? []
: oldValue,
onCleanup
])
oldValue = newValue
Expand Down

0 comments on commit 4acbf09

Please sign in to comment.