侦听单个数据 / 多个数据 /立即回调
<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>