018:尚硅谷watch监视情况2学习示例

This commit is contained in:
heiye111
2025-10-02 14:11:10 +08:00
parent de1895cf31
commit a7aea6f4de

View File

@@ -1,7 +1,9 @@
<template>
<div class="person">
<h2>{{ Sun }}</h2>
<button @click="addSun">Add Sun</button>
<h2>姓名:{{ person.name }}</h2>
<p>年龄: {{ person.age }}</p>
<button @click="changeName">Add Sun</button>
<button @click="changePerson">Change Person</button>
</div>
@@ -11,17 +13,18 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
let Sun = ref(0)
function addSun(){
Sun.value += 10
console.log(Sun.value)
let person = ref({name: 'John', age: 30})
function changeName(){
person.value.name += 'Mary张三'
console.log(person.value.name);
}
const stopWatch = watch(Sun, (newValue, oldValue) => {
console.log(`Sun changed from ${oldValue} to ${newValue}`);
if (Sun.value > 100) {
stopWatch()
}
})
function changePerson(){
person.value = {name: 'Mary332', age: 20}
}
const stopWatch = watch(person, (newValue, oldValue) => {
console.log('person的值发生了变化', newValue, oldValue);
},{deep: true})
</script>