Web Front-end
Vue.js
Learn about watchEffect in Vue3 in one article and talk about its application scenarios!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 effectsMake 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. Vue3watchEffectThe 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)The above code: When we display the 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()
})
})......Of coursewatchEffect 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!
Vue.js: Defining Its Role in Web DevelopmentApr 18, 2025 am 12:07 AMVue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.
Understanding Vue.js: Primarily a Frontend FrameworkApr 17, 2025 am 12:20 AMVue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.
Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AMNetflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.
The Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AMNetflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.
React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AMNetflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema
The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AMNetflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.
React, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AMNetflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.
Vue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AMVue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools






