<script setup lang="ts">
import { reactive, watch } from 'vue'
let person = reactive({ name: '张三', age: 18, score: { math: 90, language: 80 } })
const changeName = () => {
person.name += '='
}
const changeAge = () => {
person.age += 1
}
const changeScoreMath = () => {
person.score.math += 5
}
const changeScoreLanguage = () => {
person.score.language += 10
}
const changeScore = () => {
person.score = { math: 10, language: 10 }
}
const changePerson = () => {
Object.assign(person, { name: '李四', age: 20, score: { math: 100, language: 100 } })
}
watch([() => person.name, () => person.score], (newValue, oldValue) => {
console.log('新旧值情况一', newValue, oldValue)
})
</script>
<template>
<div>
<h1>情况二:监视【reactive】定义的【对象类型】数据中的属性</h1>
<h2>姓名:{{ person.name }}</h2>
<h2>年龄:{{ person.age }}</h2>
<h2>数学:{{ person.score.math }}</h2>
<h2>语文:{{ person.score.language }}</h2>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
<button @click="changeScoreMath">修改数学分数</button>
<button @click="changeScoreLanguage">修改语文分数</button>
<button @click="changeScore">修改分数</button>
<button @click="changePerson">修改整个人</button>
</div>
</template>
<style scoped>
button {
margin: 0 10px;
}
</style>