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>
<div class="person">
<h2>姓名:{{ person.name }}</h2>
<h2>年龄: {{ person.age }}</h2>
<button @click="changeName">Add Sun</button>
<button @click="changePerson">Change Person</button>
<h1>情况4示例</h1>
<h2>姓名{{ person.name }}</h2>
<h2>年龄{{ person.age }}</h2>
<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>
@@ -13,19 +19,42 @@
<script setup lang="ts">
import { reactive, watch } from 'vue'
let person = reactive({name: 'John', age: 30})
function changeName(){
person.name += '~'
person.age += 100
console.log(person.name);
}
function changePerson(){
Object.assign(person, {name: 'Mary', age: 20})
}
watch(person, (newValue, oldValue) => {
console.log('person的值发生了变化', newValue, oldValue);
let person = reactive({
name: 'John',
age: 25,
car: {
c1: '奔驰',
c2: '宝马'
}
})
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>