Are watchers declared in methods and onMouned auto destroyed? #7189
-
from the vue docs
what about watchers declared in inside methods or life cycle hooks? <script setup>
onMounted(() => {
watch(someRef, () => { // -------> will this watcher stop when the component is unmounted?
...
})
})
const someMethod = () => {
watch(someRef, () => { // -------> will this watcher stop when the component is unmounted?
...
})
}
</script> I realize that the code above isn't exactly clean and shouldn't be written that way to begin with, that said I still want to know what happens |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
I wrote a simple demo. It can be confirmed that watch events will always be superimposed during the life cycle. When they are destroyed, these watchers will also be destroyed. |
Beta Was this translation helpful? Give feedback.
-
My findings on this in August 2024 is that they are not destroyed immediately, when you use an inner function/event hook to create a watcher it is abstracted from the destruction chain of a component. It should be noted that I am using This behavior is obvious if you The following has a delayed destruction of its watcher, the next page resolution updating the route causes the watch to fire on exit: <script setup>
const route = useRoute()
onMounted(() => {
watch(route, (to) => {
console.log(to)
}, { immediate: true }) // I fire on entry and exit.
})
</script>
However I have not observed the next page event triggering the previous pages watcher when it is created on the top level not do i see multiple watchers being created from browser history navigation: <script setup>
const route = useRoute()
watch(route, (to) => {
console.log(to)
}, { immediate: true }) // I fire on entry only.
</script> |
Beta Was this translation helpful? Give feedback.
-
I found the reproduceable cause of watchers being fire on leave, last tested in Vue 3.5.5 If we have 3 pages A, B, C as follows: A =
Reproduction PlaygroundObserve console log outputs clicking the links in the top of this reproduction: |
Beta Was this translation helpful? Give feedback.
playground
I wrote a simple demo. It can be confirmed that watch events will always be superimposed during the life cycle. When they are destroyed, these watchers will also be destroyed.