vue3学习-watch的各种情况使用

今天在学vue3时,学到watch时,发现相对于vue2,vue3的watch有很多注意点,所以记录下来:

<template>
  <h1>我是Demo组件</h1>
  <h2>当前求和为:{{ sum }}</h2>
  <button @click="sum++">点击+1</button>
  <br />
  <h2>当前的信息是是:{{ msg }}</h2>
  <button @click="msg += '!'">点击+!</button>
  <br />
  <h2>姓名:{{ person.name }}</h2>
  <h2>年龄:{{ person.age }}</h2>
  <h2>第一份工资的薪水:{{ person.job.j1.salary }}</h2>
  <button @click="person.name += '#'">修改姓名</button>
  <button @click="person.age++">年龄+1</button>
  <button @click="person.job.j1.salary++">涨薪+1</button>
</template>
  
  <script>
import { ref, reactive, watch } from "vue";
export default {
  name: "App",
  setup() {
    let sum = ref(0);
    let msg = ref("nihao");
    let person = reactive({
      name: "张三",
      age: 18,
      job:{
        j1:{
            salary:20
        }
      }
    });

    //情况一:监视ref所定义的一个响应式数据 watch(监视的属性,回调函数,配置项)
    // watch(sum,(newValue,oldValue)=>{
    //     console.log('sun的值改变了',newValue,oldValue);
    // },{immediate:true})

    //情况二:监视ref所定义的多个响应式数据
    // watch([sum, msg], (newValue, oldValue) => {
    //   console.log("sum或msg的值改变了", newValue, oldValue);
    // });

    /**
     *情况三:监视 reactive 所定义的一个响应式数据的所有属性
      问题一 :oldValue的值等于newValue
      问题一 :关闭深度监视后(deep:false),修改 person.job.j1.salary 仍会触发监视
     */
    // watch(person,(newValue,oldValue)=>{
    //     console.log('person的值改变了',newValue,oldValue);
    // },{immediate:true,deep:false})

    //情况四:监视 reactive 所定义的一个响应式数据的某个属性
    watch(()=>person.name,(newValue,oldValue)=>{
        console.log('person的值改变了',newValue,oldValue);
    })

     //情况五:监视 reactive 所定义的一个响应式数据的某些属性
     watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{
        console.log('person的值改变了',newValue,oldValue);
    })

     //情况六:监视 reactive 所定义的一个响应式数据的对象 oldValue的值依旧等于newValue
     watch(()=>person.job,(newValue,oldValue)=>{
        console.log('person的值改变了',newValue,oldValue);
    },{deep:true}) //此处要开启深度监视

    return {
      sum,
      msg,
      person,
    };
  },
};
</script>
  
  <style>
</style>
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值