vue3 watch的用法

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默认是开启深度监听了

  • 7
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值