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