From 8904ca77c2d675707728e6a50decd3ef3370a428 Mon Sep 17 00:00:00 2001 From: Evan You Date: Fri, 8 Jul 2022 14:47:03 +0800 Subject: [PATCH] fix(watch): fix watchers triggered in mounted hook fix #12624 --- src/v3/apiWatch.ts | 4 ++-- test/unit/features/v3/apiWatch.spec.ts | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/v3/apiWatch.ts b/src/v3/apiWatch.ts index e1d7d018bf0..52be4d32e4c 100644 --- a/src/v3/apiWatch.ts +++ b/src/v3/apiWatch.ts @@ -320,8 +320,8 @@ function doWatch( } else { // pre watcher.update = () => { - if (instance && instance === currentInstance) { - // pre-watcher triggered inside setup() + if (instance && instance === currentInstance && !instance._isMounted) { + // pre-watcher triggered before const buffer = instance._preWatchers || (instance._preWatchers = []) if (buffer.indexOf(watcher) < 0) buffer.push(watcher) } else { diff --git a/test/unit/features/v3/apiWatch.spec.ts b/test/unit/features/v3/apiWatch.spec.ts index 82aba414ce0..41870ad1d51 100644 --- a/test/unit/features/v3/apiWatch.spec.ts +++ b/test/unit/features/v3/apiWatch.spec.ts @@ -1116,4 +1116,24 @@ describe('api: watch', () => { await nextTick() expect(order).toMatchObject([`mounted`, `watcher`]) }) + + // #12624 + test('pre watch triggered in mounted hook', async () => { + const spy = vi.fn() + new Vue({ + setup() { + const c = ref(0) + + onMounted(() => { + c.value++ + }) + + watchEffect(() => spy(c.value)) + return () => {} + } + }).$mount() + expect(spy).toHaveBeenCalledTimes(1) + await nextTick() + expect(spy).toHaveBeenCalledTimes(2) + }) })