Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions packages/runtime-core/__tests__/apiWatch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1205,4 +1205,39 @@ describe('api: watch', () => {
expect(countWE).toBe(3)
expect(countW).toBe(2)
})

// #5151
test('OnCleanup also needs to be cleaned,', async () => {
const spy1 = vi.fn()
const spy2 = vi.fn()
const num = ref(0)

watch(num, (value, oldValue, onCleanup) => {
if (value > 1) {
return
}
spy1()
onCleanup(() => {
// OnCleanup also needs to be cleaned
spy2()
})
})

num.value++
await nextTick()
expect(spy1).toHaveBeenCalledTimes(1)
expect(spy2).toHaveBeenCalledTimes(0)

num.value++
await nextTick()

expect(spy1).toHaveBeenCalledTimes(1)
expect(spy2).toHaveBeenCalledTimes(1)

num.value++
await nextTick()
// would not be calld when value>1
expect(spy1).toHaveBeenCalledTimes(1)
expect(spy2).toHaveBeenCalledTimes(1)
})
})
3 changes: 2 additions & 1 deletion packages/runtime-core/src/apiWatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,10 +273,11 @@ function doWatch(
getter = () => traverse(baseGetter())
}

let cleanup: () => void
let cleanup: (() => void) | undefined
let onCleanup: OnCleanup = (fn: () => void) => {
cleanup = effect.onStop = () => {
callWithErrorHandling(fn, instance, ErrorCodes.WATCH_CLEANUP)
cleanup = effect.onStop = undefined
}
}

Expand Down