vue3 watch的用法

本文详细介绍了Vue3中watch监听的各种用法,包括监听普通类型、多个普通类型、响应式对象以及对象的某个属性。还探讨了深度监听在不同情况下的表现,如当监听响应式对象时,oldValue可能无效,但可以通过监听对象的特定属性来确保oldValue的正确性。同时,展示了如何在监听嵌套对象时,Vue3默认开启深度监听。
摘要由CSDN通过智能技术生成

1.监听普通类型

const index = ref(0);
watch(index,(newValue,oldValue)=>{
  console.log("新值是"+newValue, "旧址是"+oldValue);
})

2.监听多个普通类型

const index = ref(0);
const inends = ref(0)
watch([index,inends],(newValue,oldValue)=>{
  console.log("新值是"+newValue, "旧址是"+oldValue); //返回的是一个数组
})

3.监听响应对象

const person = reactive({
   name:"柳小刀",
   age:18,
   sex:"男"
})
watch(person,(newValue,oldValue)=>{
  console.log(newValue,oldValue);
})

此时 oldValue 失效,并且强制开启了不会生效的deep,返回一个proxy对象,要想使oldValue有效需要监听响应对象的某个属性

4.监听对象的某个属性 , 第一个参数应该传入一个函数表达式

const person = reactive({
   name:"柳小刀",
   age:18,
   sex:"男"
})
watch(()=>person.name,(newValue,oldValue)=>{
  console.log(newValue,oldValue);
})

5.监听reative对象嵌套对象 此时deep是生效的

const person = reactive({
   name:"柳小刀",
   age:18,
   sex:"男",
   hobbe:{
     sing:"唱歌",
     dangce:"跳舞"
   }
})
watch(()=>person.hobbe,(newValue,oldValue)=>{
  console.log(newValue,oldValue);
})

此时oldValue有效 ,说明vue3默认是开启深度监听了

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值