How to use watch and watchEffect in vue3
First summarize the difference between the two:
1. watch is executed lazily, but watchEffect is not. Regardless of the configuration of the third parameter of watch, watch is executed when the component is first executed. It will not be executed. It will only be executed when the dependencies change later. WatchEffect is executed immediately when the program is executed here, and then executed in response to its dependency changes.
2. The two are used in different ways. Watch generally passes in two parameters. The first parameter indicates what state should trigger the listener to rerun. The second parameter defines the listener callback function. And the callback function can also accept two parameters, pointing to the values before and after the state changes, so that we can see the changes before and after the state, but we cannot see it in watchEffect, and we cannot be more specific in the first parameter like watch. Define dependencies.
3. Watch can only monitor the values defined by reactive data and ref. If you want to monitor a single value, you need to pass the getter function of the corresponding value. However, watchEffect cannot monitor the values defined by reactive and ref. It can only monitor the values defined by reactive and ref. It can monitor its corresponding specific value (it feels a bit convoluted, see the code below).
The following are some small experiments based on the third point above:
watch:
1. Let watch and watchEffect monitor the value defined by reactive:
watch:
setup() { const state = reactive({ count: 0, attr: { name: "" } }); watch(state, (post, pre) => { console.log(post); console.log(pre); console.log("watch 执行了"); }); const clickEvent = () => { state.count++; }; return { clickEvent }; }
When the clickEvent event is triggered to change the value of state.count, we can see the following results from the console, indicating that watch responded to the change in state.count, but did not do so initially. implement.
watchEffect:
setup() { const state = reactive({ count: 0, attr: { name: "" } }); watchEffect(() => { console.log("watchEffect 执行了"); console.log(state); }); const clickEvent = () => { state.count++; }; return { clickEvent }; }
Click the button multiple times to trigger the clickEvent event. The console results are as follows, indicating that watchEffect executed the callback when the component was executed for the first time. , and then no longer responds to changes in state.count.
#Explanation watch can monitor the value defined by reactive, but watchEffect cannot.
2. Let watch and watchEffect monitor the value defined by ref.
watch:
setup(){ const count = ref(0); watch(count, (post, pre) => { console.log("watch 执行了"); console.log(post); console.log(pre); }); const clickEvent = () => { count.value++; }; return { clickEvent }; }
Result:
watchEffect:
setup(){ const count = ref(0); watchEffect(() => { console.log("watchEffect 执行了"); console.log(count); }); const clickEvent = () => { count.value++; }; return { clickEvent }; }
Result:
The results are the same as above, indicating that watch can respond to the value defined by ref, but watchEffect cannot.
2. Let watch and watchEffect respond to changes in a single value:
watch:
setup(){ const state = reactive({ count: 0 }); watch(state.count, (post, pre) => { console.log("watch 执行了"); console.log(post); console.log(pre); }); const clickEvent = () => { state.count++; }; return { clickEvent }; }
The results show that no matter how the clickEvent event is triggered, the callback function in the watch will not be triggered. , nothing will be printed to the console.
watchEffect:
setup(){ const state = reactive({ count: 0 }); watchEffect(() => { console.log("watchEffect 执行了"); console.log(state.count); }); const clickEvent = () => { state.count++; }; return { clickEvent }; }
Console result:
Explanation watchEffect can respond to a single value, but watch cannot. If you want watch In response to changes in count, you need to pass in the getter function as the first parameter, as follows:
setup(){ const state = reactive({ count: 0 }); watch( () => state.count, (post, pre) => { console.log("watch 执行了"); console.log(post); console.log(pre); } ); const clickEvent = () => { state.count++; }; return { clickEvent }; }
If the getter function returns the state reference value, the state reference will not be modified when changing state.count value, so it will not respond to changes in state.count. If you want to respond, you need to pass in the third parameter configuration {deep:true}. At the same time, the values of post and pre in the code are the same, as follows:
setup(){ const state = reactive({ count: 0 }); //不会响应变化 watch( () => state, (post, pre) => { console.log("watch 执行了"); console.log(post); console.log(pre); } ); const clickEvent = () => { state.count++; }; return { clickEvent }; }
setup(){ const state = reactive({ count: 0 }); //加上了 {deep:true} 可以响应变化 watch( () => state, (post, pre) => { console.log("watch 执行了"); console.log(post); console.log(pre); }, {deep:true} ); const clickEvent = () => { state.count++; }; return { clickEvent }; }
If a reference value is returned, and you need to compare different values before and after the change, you need to pass in the getter function to return the value after a deep copy of the object. In the following example, an array is returned:
setup(){ const state = reactive({ count: 0 }); const numbers = reactive([0, 1, 2, 3]); watch( () => [...numbers], (post, pre) => { console.log("watch 执行了"); console.log(post); console.log(pre); } ); const clickEvent = () => { numbers.push(1); }; return { clickEvent }; }
Control Taiwan’s result:
The above is the detailed content of How to use watch and watchEffect in vue3. 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



You may have encountered the problem of green lines appearing on the screen of your smartphone. Even if you have never seen it, you must have seen related pictures on the Internet. So, have you ever encountered a situation where the smart watch screen turns white? On April 2, CNMO learned from foreign media that a Reddit user shared a picture on the social platform, showing the screen of the Samsung Watch series smart watches turning white. The user wrote: "I was charging when I left, and when I came back, it was like this. I tried to restart, but the screen was still like this during the restart process." Samsung Watch smart watch screen turned white. The Reddit user did not specify the smart watch. Specific model. However, judging from the picture, it should be Samsung Watch5. Previously, another Reddit user also reported

vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

Preface Whether it is vue or react, when we encounter multiple repeated codes, we will think about how to reuse these codes instead of filling a file with a bunch of redundant codes. In fact, both vue and react can achieve reuse by extracting components, but if you encounter some small code fragments and you don’t want to extract another file, in comparison, react can be used in the same Declare the corresponding widget in the file, or implement it through renderfunction, such as: constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

Using Vue to build custom elements WebComponents is a collective name for a set of web native APIs that allow developers to create reusable custom elements (customelements). The main benefit of custom elements is that they can be used with any framework, even without one. They are ideal when you are targeting end users who may be using a different front-end technology stack, or when you want to decouple the final application from the implementation details of the components it uses. Vue and WebComponents are complementary technologies, and Vue provides excellent support for using and creating custom elements. You can integrate custom elements into existing Vue applications, or use Vue to build
