Greetings,
I am using watchEffect in a component that is loaded by router-view.
After the route is changed, this component is unmounted.
I was expecting onCleanup to fire at this time.
Is this a correct expectation?
To my humble information, vue-router does not cache routing components, so I am assuming they are being destroyed. If that is not the case, then how can I ensure proper cleanup while leveraging the router's cache?
Btw., the Vue Composition API official documentation is calling onCleanup as onInvalidate which was a bit confusing to me. May be I was on the wrong docs version.
Thank you.
Yes it should be called, provided that the watchEffect was created inside of setup(). Can you provide a reproduction?
My code also doesn't work ...
import { watchEffect, defineComponent } from '@vue/composition-api'
const listenOutsideRef = (handler, event, ref) => {
if (!ref || ref.contains(event.target)) {
console.log('no ref')
return
}
handler(event)
}
const onClickOutside = (
refs,
refName,
handler,
) => {
watchEffect(onCleanup => {
if (refs && refs[refName]) {
const func = event => listenOutsideRef(handler, event, refs[refName])
document.addEventListener('click', func)
// not work 馃槩
onCleanup(() => {
console.log('destroy')
document.removeEventListener('click', func)
})
}
})
}
export default defineComponent({
setup(_props, ctx) {
onClickOutside(ctx.refs, 'myRef', () => {
console.log('on click outside')
})
},
})
<template>
<div ref="myRef" />
</template>
Thanks. Confirmed and found the cause. Will submit a fix later this evening.
PR done.
Note: I think the normal watch had the same bug, as the modified test failed just the same. Need someone else to have a second look though.
Most helpful comment
Thanks. Confirmed and found the cause. Will submit a fix later this evening.