Home > Web Front-end > Vue.js > body text

How to use watch and watchEffect in vue3

王林
Release: 2023-05-11 12:37:06
forward
1623 people have browsed it

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 };
}
Copy after login

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.

How to use watch and watchEffect in vue3

watchEffect:

setup() {
    const state = reactive({ count: 0, attr: { name: "" } });
    watchEffect(() => {
        console.log("watchEffect 执行了");
        console.log(state);
    });
    const clickEvent = () => {
        state.count++;
    };
    return { clickEvent };
}
Copy after login

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.

How to use watch and watchEffect in vue3

#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 };
}
Copy after login

Result:

How to use watch and watchEffect in vue3

watchEffect:

setup(){
    const count = ref(0);
    watchEffect(() => {
      console.log("watchEffect 执行了");
      console.log(count);
    });
    const clickEvent = () => {
      count.value++;
    };
    return { clickEvent };
}
Copy after login

Result:

How to use watch and watchEffect in vue3

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 };
}
Copy after login

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 };
}
Copy after login

Console result:

How to use watch and watchEffect in vue3

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 };
}
Copy after login

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 };
}
Copy after login
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 };
}
Copy after login

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 };
}
Copy after login

Control Taiwan’s result:

How to use watch and watchEffect in vue3

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template