020:尚硅谷watch监视情况4学习示例

This commit is contained in:
heiye111
2025-10-02 15:15:48 +08:00
parent 5391058445
commit 22857ff559

View File

@@ -1,10 +1,16 @@
<template> <template>
<div class="person"> <div class="person">
<h2>姓名:{{ person.name }}</h2> <h1>情况4示例</h1>
<h2>年龄: {{ person.age }}</h2> <h2>姓名{{ person.name }}</h2>
<button @click="changeName">Add Sun</button> <h2>年龄{{ person.age }}</h2>
<button @click="changePerson">Change Person</button> <h2>汽车{{ person.car.c1 }}---{{ person.car.c2 }} </h2>
<button @click="changeName">更改姓名</button>
<button @click="changeAge">更改年龄</button>
<button @click="changeCarc1">更改汽车品牌1</button>
<button @click="changeCarc2">更改汽车品牌2</button>
<button @click="changeCar">更改所有汽车</button>
</div> </div>
@@ -13,19 +19,42 @@
<script setup lang="ts"> <script setup lang="ts">
import { reactive, watch } from 'vue' import { reactive, watch } from 'vue'
let person = reactive({name: 'John', age: 30}) let person = reactive({
function changeName(){ name: 'John',
person.name += '~' age: 25,
person.age += 100 car: {
console.log(person.name); c1: '奔驰',
} c2: '宝马'
function changePerson(){ }
Object.assign(person, {name: 'Mary', age: 20})
}
watch(person, (newValue, oldValue) => {
console.log('person的值发生了变化', newValue, oldValue);
}) })
function changeName(){
person.name += 'Jane'
}
function changeAge(){
person.age += 30
}
function changeCarc1(){
person.car.c1 = '大众'
}
function changeCarc2(){
person.car.c2 = '奥迪'
}
function changeCar(){
person.car = {
c1: '保时捷',
c2: '法拉利'
}
}
watch(()=>person.age, (newValue, oldValue) => {
console.log('person changed:', newValue, oldValue)
})
watch(()=>person.car, (newValue, oldValue) => {
console.log('汽车变化了:', newValue, oldValue)
},{deep:true})
</script> </script>