Skip to content

Commit 8904ca7

Browse files
committed
fix(watch): fix watchers triggered in mounted hook
fix #12624
1 parent 012e10c commit 8904ca7

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

src/v3/apiWatch.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,8 @@ function doWatch(
320320
} else {
321321
// pre
322322
watcher.update = () => {
323-
if (instance && instance === currentInstance) {
324-
// pre-watcher triggered inside setup()
323+
if (instance && instance === currentInstance && !instance._isMounted) {
324+
// pre-watcher triggered before
325325
const buffer = instance._preWatchers || (instance._preWatchers = [])
326326
if (buffer.indexOf(watcher) < 0) buffer.push(watcher)
327327
} else {

test/unit/features/v3/apiWatch.spec.ts

+20
Original file line numberDiff line numberDiff line change
@@ -1116,4 +1116,24 @@ describe('api: watch', () => {
11161116
await nextTick()
11171117
expect(order).toMatchObject([`mounted`, `watcher`])
11181118
})
1119+
1120+
// #12624
1121+
test('pre watch triggered in mounted hook', async () => {
1122+
const spy = vi.fn()
1123+
new Vue({
1124+
setup() {
1125+
const c = ref(0)
1126+
1127+
onMounted(() => {
1128+
c.value++
1129+
})
1130+
1131+
watchEffect(() => spy(c.value))
1132+
return () => {}
1133+
}
1134+
}).$mount()
1135+
expect(spy).toHaveBeenCalledTimes(1)
1136+
await nextTick()
1137+
expect(spy).toHaveBeenCalledTimes(2)
1138+
})
11191139
})

0 commit comments

Comments
 (0)