fix(watch): fix watchers triggered in mounted hook

fix #12624
This commit is contained in:
Evan You 2022-07-08 14:47:03 +08:00
parent 012e10c9ca
commit 8904ca77c2
2 changed files with 22 additions and 2 deletions

View File

@ -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 {

View File

@ -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)
})
})