vue3中watch监听reactive数据和ref

  • Post author:
  • Post category:vue


vue3中watch监听reactive数据的6种场景

<template>
  <h2>当前求和为:{{sum}}</h2>
  <button @click="sum++">点我加</button>
  <hr>
  <h2>{{msg}}</h2>
  <hr>
  <h2>{{person.name}}</h2>
  <h2>{{person.age}}</h2>
  <h2>{{person.jap.a.b}}</h2>
  <button @click="person.name+='2'">改变名字</button>
  <button @click="person.age+=1">改变年龄</button>
  <button @click="person.jap.a.b+=1">改变b</button>
</template>
<script>
import {reactive, ref, watch} from 'vue'
export default {
  name: "app",
  setup() {
      let sum = ref(0);
      let msg = ref('nihao');
      let person = reactive({
        name:'张三',
        age:123,
        jap:{
          a:{
            b:10
          }
        }
      })
      // 情况1,监视ref定义的响应数据
      watch(sum,(oldvalue,newvalue)=>{
           console.log(oldvalue,newvalue)
      },{immediate:true})
      // 情况二,监听ref所定义的多个响应式数据
      watch([msg,sum],(oldvalue,newvalue)=>{
           console.log(oldvalue,newvalue)
      },{immediate:true})
      //情况三,监听 reactive 所定义的一个响应式数据,注意此处无法获得oldvalue
        // 1,注意:此处无法正确的获取oldValue
        // 2,注意:强制开启深度监听
      watch(person,(oldvalue,newvalue)=>{
            console.log(oldvalue,newvalue)
      })
      //情况四:监听reactive所定义的一个响应式数据中的某个属性
      watch(()=>person.name,(oldvalue,newvalue)=>{
            console.log(oldvalue,newvalue)
      })

      //情况五:监听reactive所定义的一个响应式数据中的某些属性
      watch([()=>person.name,()=>person.age],(oldvalue,newvalue)=>{
            console.log(oldvalue,newvalue)
      })

      // 情况六:特殊情况
      watch(()=>person.jap,(oldvalue,newvalue)=>{
            console.log(oldvalue,newvalue)
      },{deep:true})//由于此处监视的是reactive所定义的对象中的某个属性,所以deep配置无效
      return{
            sum,
            msg,
            person
      }
  },
};
</script>

<style lang="scss"></style>


watch监听函数 (ref篇)

<template>
  <h1>ref基础数据类型监听</h1>
  <h2>姓名:{{ name }}</h2>
  <h2>年龄:{{ age }}</h2>
  <button @click="name = '李四'">改变姓名</button>
  <button @click="age += 1">改变年龄</button>
</template>
 
<script>
import { ref, watch } from "vue";
export default {
  name: "Demo",
  setup() {
    let name = ref("张三");
    let age = ref(18);
 
    /* watch 接收三个参数
            1.要监听的对象
            2.监听的数据变化的回调函数
            3.监听函数的一些配置(deep,immediate ,flush ...)
    */
 
    // 1.监听ref基本数据类型 --单个数据
    watch(name, (newVal, oldVal) => {
      console.log("name变化了:", newVal, oldVal);
    });
    watch(age, (newVal, oldVal) => {
      console.log("age变化了:", newVal, oldVal);
    });
 
    //2.监听ref多个值得变化
    watch([name, age], (newVal, oldVal) => {
      console.log("[name,age]变化了:", newVal, oldVal);
    });
 
    return {
      name,
      age,
    };
  },
};
</script>