<script setup lang="ts">
import { ref, watch } from 'vue'
let person = ref({ name: '张三', age: 18 })
const changeName = () => {
person.value.name += '='
}
const changeAge = () => {
person.value.age += 1
}
const changePerson = () => {
person.value = { name: '李四', age: 20 }
}
watch(person, (newValue, oldValue) => {
console.log('新旧值情况一', newValue, oldValue)
})
watch(
person,
(newValue, oldValue) => {
console.log('新旧值情况二', newValue, oldValue)
},
{ deep: true }
)
watch(
person,
(newValue, oldValue) => {
console.log('新旧值情况三', newValue, oldValue)
},
{ deep: true, immediate: true }
)
</script>
<template>
<div>
<h1>情况二:监视【ref】定义的【对象类型】数据</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="changePerson">修改整个人</button>
</div>
</template>
<style scoped>
button {
margin: 0 10px;
}
</style>