7

According to Vue3 Doc, watchEffect will stop when a component is unmounted.

When watchEffect is called during a component's setup() function or lifecycle hooks, the watcher is linked to the component's lifecycle and will be automatically stopped when the component is unmounted.

Does watch has the same behavior in term of automatically stoppage? Thanks!

mannok
  • 1,712
  • 1
  • 20
  • 30
  • 2
    It seems so. See https://v3.vuejs.org/guide/reactivity-computed-watchers.html#shared-behavior-with-watcheffect. – User 28 Apr 12 '21 at 04:45
  • @User28 It did mention `watch shares behavior with watchEffect in terms of manual stoppage`. Seems for manual stoppage but not automatically stoppage – mannok Apr 12 '21 at 06:30
  • 3
    Umm, I was confused too. The `manual stoppage` links to the `Stopping the Watcher` which talk about automatically stopped. I create [this](https://jsfiddle.net/wmbvzsn7/) to test. It seems that the watcher automatically stopped when the component is unmounted. – User 28 Apr 12 '21 at 10:02
  • @User28 This is the answer. Thanks for you fiddle. – mannok Apr 12 '21 at 10:29

1 Answers1

2

Watchers declared synchronously inside setup() or are bound to the owner component instance, and will be automatically stopped when the owner component is unmounted. In most cases, you don't need to worry about stopping the watcher yourself.

Src: https://vuejs.org/guide/essentials/watchers.html#stopping-a-watcher

So the answer seems like, yes if you declare the watcher synchronously, and no if you declare it asynchronously.

It looks like watch()/watchEffect() return unwatch() functions that you have to call to stop asynchronously created watchers.

PS
This was mainly just a follow-up on @User28. The link in your comment was outdated but I couldn't edit it.

Tom
  • 471
  • 3
  • 11