As many of you know, Vue supports adding watchers using the declarative Single File Component API using the watch property, like so:
watch: {
// whenever question changes, this function will run
question: function (newQuestion, oldQuestion) {
this.answer = 'Waiting for you to stop typing...'
this.debouncedGetAnswer()
}
},
I'm relatively sure that following this approach, Vue takes care of the cleanup on component destroyed(). However, due to several reasons, I'm in need to add watchers dynamically using the vm.$watch API, like so:
// keypath
vm.$watch('a.b.c', function (newVal, oldVal) {
// do something
})
I know that the vm.$watch function returns an unwatch() function I can call, but I'm curious if this is strongly necessary to avoid things like memory leaks. I would think that on component destroyed, these watchers should stop existing as well since I think these watchers exist on component instance, but I'm not really sure. Also, nothing in the Vue.js docs or style guide mention that not calling unwatch() could lead to issues, which makes me think that I really shouldn't worry about not calling unwatch() on component destroyed().
Does someone have a more conclusive answer to this question?
I got the following response from the VueLand Discord from user Cathrine with the MVP role.
it should be attached to the vm you're calling it on. So when the vm is destroyed, so is the watcher. {...} As you programmatically create the watcher, it makes sense to have a way to programmatically stop it. Afaik, that's the only purpose of it.
This, combined with @Asimple 's response seem to point that maybe I shouldn't worry about this too much. Thanks for your time everyone
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With