1.只侦听单个属性
<template>
<p>{{num}}</p>
<button @click="add">侦听单个值的变化</button>
</template>
<script setup>
import { ref , watch } from 'vue'
const num = ref(0)
const add = () => {
num.value++
}
watch(num , (newValue , oldValue) => {
console.log(`num值的变化,${newValue},${oldValue}`)
})
</script>
2.watch侦听器侦听多个属性的变化
<template>
<p>{{num}}</p>
<p>{{age}}</p>
<button @click="add">修改num的值</button>
<button @click="update">修改name的值</button>
</template>
<script setup>
import {ref , reactive , watch } from 'vue'
const num = ref(0)
const name = ref("小明")
const add = () => {
num.value++
}
const update = () => {
name.value = "小张"
}
watch([num , name],([NewNum , NewName] , [oldNum , oldName]) => {
console.log(`num , name值的改变 , ${newNum , NewName} , ${oldNum , oldName }`)
}
</script>
3.watch侦听对象的变化
<template>
<p>{{}}</p>
</template>
<script setup>
import { reactive , watch } from "vue"
const person = reactive({
name:"小明",
age:18
})
watch(() => person.age,() => {
console.log(`侦听对象的变化 ${ person.age }`)
})
</script>