Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use watchEffect in Vue3

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "how to use watchEffect in Vue3". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor learn how to use watchEffect in Vue3.

Preface

WatchEffect, which immediately executes a function passed in, responsively tracks its dependencies, and reruns the function when its dependency changes.

In other words: watchEffect is equivalent to merging the dependent source of watch with the callback function, which will be re-executed when any responsive dependency updates you use. Callback functions that are different from watch,watchEffect are executed immediately (that is, {immediate: true})

Side effects of watchEffect

What is the side effect (side effect), simply speaking, the side effect is to perform some operation, such as the modification of external variable data or variables, the call of external interface, and so on. The callback function of watchEffect is a side effect function, because we use watchEffect to listen for changes in dependencies and perform some actions.

When executing a side effect function, it is bound to have some impact on the system, such as executing a timer setInterval in the side effect function, so we have to deal with the side effect. The function passed in by Vue3's watchEffect snooping side effect can take an onInvalidate function as an input parameter to register the callback when the cleanup fails. This failure callback is triggered when the following occurs:

When the side effect is about to be re-executed (that is, the value of the dependency changes)

The listener is stopped (stop listening by displaying the return value of the call, or implicitly calling stop listening when the component is unloaded)

Import {watchEffect, ref} from 'vue'const count = ref (0) watchEffect ((onInvalidate) = > {console.log (count.value) onInvalidate () = > {console.log (' onInvalidate' executed)})}) setTimeout (() = > {count.value++}, 1000)

The above code is printed in the following order: 0-> executed onInvalidate, and finally executed-> 1

Analysis: first print the value 0 of count during initialization, and then because the timer updates the value of count to 1, the side effect is about to be re-executed, so the callback function of onInvalidate will be triggered, the onInvalidate will be printed, and then the side effect function will be executed to print the value of count 1.

Import {watchEffect, ref} from 'vue'const count = ref (0) const stop = watchEffect ((onInvalidate) = > {console.log (count.value) onInvalidate (()) = > {console.log (' onInvalidate' executed)})) setTimeout (() = > {stop ()}, 1000)

The above code: when we show that the stop function is executed to stop listening, the callback function of onInvalidate will also be triggered. Similarly, when the component where watchEffect is uninstalled, the stop function is implicitly called to stop listening, so the callback function of onInvalidate can also be triggered.

Application of watchEffect

What can we do with the non-lazy execution of watchEffect and the onInvalidate function passed in?

Scenario 1: usually we define a timer or listen for an event. We need to define or register it in the mounted lifecycle hook function, and then clear the timer or cancel the listening in the beforeUnmount hook function before the component is destroyed. In doing so, our logic is scattered over two life cycles, which is not conducive to maintenance and reading.

If I use watchEffect and put the creation and destruction logic together, the code is more elegant and easier to read.

/ / timer registers and destroys watchEffect ((onInvalidate) = > {const timer = setInterval (() = > {/ /...}, 1000) onInvalidate (() = > clearInterval (timer))}) const handleClick = () = > {/ /...} / / dom snooping and unsnooping onMounted (() = > {watchEffect ((onInvalidate) = > {document.querySelector ('.btn'). AddEventListener ('click', handleClick) False) onInvalidate (() = > document.querySelector ('.btn'). RemoveEventListener ('click', handleClick)})})

Scenario 2: use watchEffect as an anti-jitter throttle (such as canceling a request)

Const id = ref (13) watchEffect (onInvalidate = > {/ / Asynchronous request const token = performAsyncOperation (id.value) / / if the id changes frequently, the invalidation function will be triggered and the previous API request onInvalidate () = > {/ / id has changed or watcher is stopped will be cancelled. / / invalidate previously pending async operation token.cancel ()}) at this point, I believe you have a deeper understanding of "how to use watchEffect in Vue3". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report