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

How to use watch in Vue3

WBOY
Release: 2023-05-12 09:49:05
forward
1798 people have browsed it

    # The watch function is used to listen for changes in a certain value. When the value changes, the corresponding processing logic is triggered.

    1. Basic examples of watch

    <template>
      <div>
        <div>{{ count }}</div>
        <button @click="changCount">更改count的值</button>
      </div>
    </template>
     
    <script setup>
    import {ref,reactive, watch} from &#39;vue&#39;
    const count = ref(0)
    function changCount(){
      count.value++
    }
    watch(count,(newValue,oldValue)=>{
      if(newValue){
        console.log(`我侦听到了count状态的变化,当前值为${newValue},从而处理相关逻辑`);
      }
    })
    </script>
     
    <style>
     
    </style>
    Copy after login

    2. Watch monitors multiple data

    getter function:

    <template>
      <div>
        <div>{{ x }}</div>
        <button @click="changCount">更改count的值</button>
      </div>
    </template>
     
    <script setup>
    import { ref, reactive, watch } from "vue";
    const x = ref(1);
    const y = ref(5);
    function changCount() {
      x.value++;
    }
    watch(
      () => x.value + y.value,
      (sum) => {
        console.log(`我是x与y之和${sum}`);
      }
    );
    </script>
     
    <style>
    </style>
    Copy after login

    Array composed of multiple sources

    <template>
      <div>
        <div>{{ x }}</div>
        <button @click="changCount">更改count的值</button>
      </div>
    </template>
     
    <script setup>
    import { ref, reactive, watch } from "vue";
    const x = ref(1);
    const y = ref(5);
    function changCount() {
      x.value++;
    }
    watch(
      [x,y],
      ([x,y]) => {
        console.log(`我是x=>${x},我是y=》${y}`);
      }
    );
    </script>
     
    <style>
    </style>
    Copy after login

    3. The value of the watch monitoring object

    <template>
      <div>
        <div>{{ obj.name }}</div>
        <button @click="changObj">更改count的值</button>
      </div>
    </template>
     
    <script setup>
    import { ref, reactive, watch } from "vue";
    const obj = ref({name:&#39;你好&#39;})
    function changObj(){
      obj.value.name+=&#39;我不好&#39;
    }
    watch(()=>obj.value.name,(name)=>{
      console.log(name);
    })
    </script>
     
    <style>
    </style>
    Copy after login

    4. The configuration parameters of the watch listener

    1.deep

    is used to enable deep monitoring

    <template>
      <div>
        <div>{{ obj.name }}</div>
        <button @click="changObj">更改count的值</button>
      </div>
    </template>
     
    <script setup>
    import { ref, reactive, watch, watchEffect } from "vue";
    const obj = ref({name:&#39;你好&#39;})
    function changObj(){
      obj.value.name+=&#39;我不好&#39;
    }
    // obj是一个RefImpl对象,当不开启深度监听的时候,监听obj无法检测到obj属性的变化
    watch(obj,()=>{
      console.log(obj.value.name);
    }, { deep: true })
    </script>
     
    <style>
    </style>
    Copy after login

    2.immediate

    Whether to enable initialization detection. By default, the method in the listener will be executed only when the value changes. After immediate is enabled, initialization will be executed once.

    <template>
      <div>
        <div>{{ obj.name }}</div>
        <button @click="changObj">更改count的值</button>
      </div>
    </template>
     
    <script setup>
    import { ref, reactive, watch, watchEffect } from "vue";
    const obj = ref({name:&#39;你好&#39;})
    function changObj(){
      obj.value.name+=&#39;我不好&#39;
    }
    // obj是一个RefImpl对象,当不开启深度监听的时候,监听obj无法检测到obj属性的变化
    watch(obj,()=>{
      console.log(obj.value.name);
    }, { deep: true,immediate:true })
    </script>
     
    <style>
    </style>
    Copy after login

    5. Simplify watch through watchEffect()

    It is common for listener callbacks to use exactly the same reactive state as the source. For example:

    <template>
      <div>
        <div>{{ obj.name }}</div>
        <button @click="changObj">更改count的值</button>
      </div>
    </template>
     
    <script setup>
    import { ref, reactive, watch, watchEffect } from "vue";
    const obj = ref({name:&#39;你好&#39;})
    function changObj(){
      obj.value.name+=&#39;我不好&#39;
    }
    watch(obj.value,()=>{
      console.log(obj.value.name);
    })
    </script>
     
    <style>
    </style>
    Copy after login

    We can use the watchEffect function to simplify the above code. watchEffect() Allows us to automatically track reactive dependencies of callbacks. The above listener can be rewritten as:

    <template>
      <div>
        <div>{{ obj.name }}</div>
        <button @click="changObj">更改count的值</button>
      </div>
    </template>
     
    <script setup>
    import { ref, reactive, watch, watchEffect } from "vue";
    const obj = ref({name:&#39;你好&#39;})
    function changObj(){
      obj.value.name+=&#39;我不好&#39;
    }
    // watch(obj.value,()=>{
    //   console.log(obj.value.name);
    // })
    watchEffect(()=>{
      console.log(obj.value.name);
    })
    </script>
     
    <style>
    </style>
    Copy after login

    Note: It should be noted that the watchEffect callback will be executed immediately, and there is no need to specify immediate

    6. watch vs. watchEffect

    ## Both #watch and watchEffect can execute callbacks with side effects reactively. The main difference between them is the way reactive dependencies are tracked:

    • watch only tracks data sources that are explicitly listened to. It won't track anything accessed in the callback. Additionally, the callback is only fired when the data source actually changes. watch avoids tracking dependencies when side effects occur, so we can more precisely control when the callback function is triggered.

    • watchEffect will track dependencies during the occurrence of side effects. It will automatically track all accessible reactive properties during synchronization. This is more convenient and the code tends to be cleaner, but sometimes its reactive dependencies are less clear.

    7. Callback triggering mechanism and stopping the listener

    If you want to access the DOM updated by Vue in the listener callback, you need to specify flush: ' post' option:

    watch(source, callback, {
      flush: &#39;post&#39;
    })
     
    watchEffect(callback, {
      flush: &#39;post&#39;
    })
    Copy after login

    Stop listening

    Listeners created using synchronous statements in setup() or
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template