


Learn about watchEffect in Vue3 in one article and talk about its application scenarios!
This article will take you to understand watchEffect in Vue3, introduce its side effects, and talk about what it can do. I hope it will be helpful to everyone!
watchEffect
, which immediately executes a function passed in while reactively tracking its dependencies and re-running the function when its dependencies change. (Learning video sharing: vue video tutorial)
In other words: watchEffect
is equivalent to merging the dependency source and callback function of watch
, This callback function is re-executed when any of your reactive dependencies are updated. Different from watch
, the callback function of watchEffect
will be executed immediately (i.e. { immediate: true }
)
This article mainly describes how to use Clear side effects
Make our code more elegant~
watchEffect's side effects
What are side effects (side effect
), Simply put, a side effect is to perform a certain operation, such as modification of external variable data or variables, call of external interface, etc. The callback function of watchEffect
is a side effect function, because we use watchEffect
to perform certain operations after listening to changes in dependencies.
When a side effect function is executed, it will inevitably have some impact on the system. For example, a timer setInterval
is executed in the side effect function, so we must deal with the side effects. Vue3
watchEffect
The function that listens for side effects can receive an onInvalidate
function as an input parameter to register a callback when the cleanup fails. This invalidation callback will be triggered when the following situations occur:
- The side effect is about to be re-executed (that is, the value of the dependency changes)
- The listener is stopped (returned by the explicit call The value stops listening, or the component is uninstalled and the stop listening is called implicitly)
import { watchEffect, ref } from 'vue' const count = ref(0) watchEffect((onInvalidate) => { console.log(count.value) onInvalidate(() => { console.log('执行了onInvalidate') }) }) setTimeout(()=> { count.value++ }, 1000)
The order in which the above code is printed is: 0
-> Executed onInvalidate, and finally execute
-> 1
Analysis: During initialization, the value of count
is first printed 0
, and then due to the timer Update the value of count
to 1
. At this time, the side effect will be executed again, so the callback function of onInvalidate
will be triggered and executed onInvalidate# will be printed. ##, and then executes the side effect function and prints the value
1 of
count.
import { watchEffect, ref } from 'vue' const count = ref(0) const stop = watchEffect((onInvalidate) => { console.log(count.value) onInvalidate(() => { console.log('执行了onInvalidate') }) }) setTimeout(()=> { stop() }, 1000)
stop function to stop listening, the
onInvalidate callback function will also be triggered. Similarly, when the component where
watchEffect is located will implicitly call the stop
function to stop listening, so the callback of
onInvalidate can also be triggered. function.
watchEffect application
Using the non-lazy execution ofwatchEffect and the passed in
onInvalidate function, we can do What happened?
Scenario 1: Usually we define a timer or listen for an event. We need to define or register it in the mounted life cycle hook function, and then the component is destroyed Previously, the timer was cleared or the listening function was cleared in the
beforeUnmount hook function. In this way, our logic is scattered in two life cycles, which is not conducive to maintenance and reading.
watchEffect, the creation and destruction logic are put together, and the code is more elegant and easy to read~
// 定时器注册和销毁 watchEffect((onInvalidate) => { const timer = setInterval(()=> { // ... }, 1000) onInvalidate(() => clearInterval(timer)) }) const handleClick = () => { // ... } // dom的监听和取消监听 onMounted(()=>{ watchEffect((onInvalidate) => { document.querySelector('.btn').addEventListener('click', handleClick, false) onInvalidate(() => document.querySelector('.btn').removeEventListener('click', handleClick)) }) })
Scenario 2: Use watchEffect to make an anti-shake throttling (such as canceling a request)
const id = ref(13) watchEffect(onInvalidate => { // 异步请求 const token = performAsyncOperation(id.value) // 如果id频繁改变,会触发失效函数,取消之前的接口请求 onInvalidate(() => { // id has changed or watcher is stopped. // invalidate previously pending async operation token.cancel() }) })
watchEffect can also do many things, such as opening a modification In the
modal pop-up window, if a change in
id is detected, we can reset the initial parameters in the
onInvalidate function... This is just an introduction, I hope everyone will discover more~
web front-end development, Basic programming video)
The above is the detailed content of Learn about watchEffect in Vue3 in one article and talk about its application scenarios!. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.
