【一】监听对象类型
<script setup>
import {reactive, ref, watch} from "vue";
const age=ref(10)
const person=reactive({
name:'hope',
age:19
})
const changeAge=()=>{
age.value+=1
}
const changeName=()=>{
person.name='彭于晏'
person.age+=10
}
watch(age,(newValue,oldValue)=>{
console.log('age变化了',newValue,oldValue)
})
watch(()=>person.name,(newValue,oldValue)=>{
console.log('name变化了',newValue,oldValue)
})
</script>
<template>
<div>
<h1>年龄: {{age}}</h1>
<h1>姓名: {{person.name}}</h1>
<p><button @click="changeAge">点我改变年龄</button></p>
<p><button @click="changeName">点我改变名字</button></p>
</div>
</template>
【二】监听多个变量
// 监听多个
const sum = ref(100)
const msg = ref('很好')
watch([sum, msg], (newValue, oldValue) => {
console.log('sum或msg变化了', newValue, oldValue)
})
watch(()=>[person.name,person.age],(newValue,oldValue)=>{
console.log('多个变化了',newValue,oldValue)
})
【三】watchEffect函数
- watchEffect 使用:不用指定监听谁,只要watchEffect内部用了某个变量,某个变量发送变化,就会触发
watchEffect(() => {
const x1 = person.age
const x2 = person.name
console.log('watchEffect配置的回调执行了')
})