vue3--组合式API-watch

侦听单个数据 / 多个数据 /立即回调

<script setup>
import { ref ,watch} from "vue";
const count = ref(0)
const nickname = ref('张三')


const changeCount=()=>{
  count.value++
}
const changeNickName =()=>{
  nickname.value = '李四'
}


// 1. 监视单个数据 :  watch(ref对象,(newValue,oldValue)=>{.....})
 watch(count,(newValue,oldValue)=>{
   console.log(newValue,oldValue)//1 0
})
// 2. 监视多个数据: watch(【ref对象,ref对象)】,(newValue,oldValue)=>{....}
watch([count,nickname],(newArr,oldArr)=>{
   console.log(newArr,oldArr)
// 3.immediate--在创建侦听器时立即触发回调
 watch(count,(newValue,oldValue)=>{
   console.log(newValue,oldValue)
 },{
   immediate:true,
 }
 )


</script>
<template>
  <div>{{ count }}</div>
  <button @click="changeCount">改数字</button>
  <div>{{ nickname }}</div>
  <button @click="changeNickName">改昵称</button>

  
</template>

 深度侦听deep

<script setup>
import { ref ,watch} from "vue";


// 4.deep深度监视--由于默认watch是浅层监视,
// const数据ref= ref(简单类型),可以直接监视 
// but  如果const2 数据ref = ref(复杂类型),监视不到

 const userInfo = ref({
   name:'zs',
   age:18
 })
 const  setUserInfo=()=>{
   userInfo.value.age++
  userInfo.value.name='ls'
}
 watch(userInfo,(newValue)=>{
  console.log(newValue);//没有deep:true监视不到,修改整个userInfo整个对象才能监视

 },{
   deep:true
 })

</script>

<template>
 
  <div>{{ userInfo }}</div>
  <button @click="setUserInfo">修改userinfo</button>
</template>

精确侦听对象的某一个属性

<script setup>
import { ref ,watch} from "vue";

//5.精确侦听对象的某一个属性
 const userInfo = ref({
  name:'zs',
  age:18
})
const  setUserInfo=()=>{
  userInfo.value.age++
  userInfo.value.name='ls'
}
watch(
  ()=> userInfo.value.name,
  ()=>console.log('发生了变化')
)


</script>
<template>
 
  <div>{{ userInfo }}</div>
  <button @click="setUserInfo">修改userinfo</button>
</template>

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值