Home >Web Front-end >Vue.js >How to use watch in Vue3

How to use watch in Vue3

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBforward
2023-05-12 09:49:051854browse

    # 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>

    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>

    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>

    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>

    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>

    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>

    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>

    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>

    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;
    })

    Stop listening

    Listeners created using synchronous statements in setup() or 5101c0cdbdc49998c642c71f6b6410a8 will be automatically bound to the host component instance, and Will automatically stop when the host component is uninstalled. Therefore, in most cases you don't need to worry about stopping a listener.

    One key point is that the listener must be created with a synchronous statement: if you create a listener with an asynchronous callback, then it will not be bound to the current component and you must stop it manually to prevent memory leakage. As an example below:

    // ...当该侦听器不再需要时
    unwatch()

    The above is the detailed content of How to use watch in Vue3. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete