watch监视:情况一、情况二
情况一:【ref】对【基本数据】类型的监视
<template>
<div class="person">
<h2>sum的值为:{{ sum }}</h2>
<button @click="changSum">点我加一</button>
</div>
</template>
<script lang="ts" setup name="Person">
import{ref,watch} from 'vue'
let sum=ref(0);
const stopWatch=watch(sum,(newValue,oldValue)=>{
console.log('sum变化了',newValue,oldValue)
})
if(sum.value>10){
stopWatch()
}
function changSum(){
sum.value++
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 5px;
padding: 20px;
}
button{
margin: 0 5px;
}
</style>
情况二:【ref】对【对象数据】类型的监视
<template>
<div class="person">
<h2>sum的值为:{{ sum }}</h2>
<button @click="changSum">点我加一</button>
</div>
</template>
<script lang="ts" setup name="Person">
import{ref,watch} from 'vue'
let sum=ref(0);
const stopWatch=watch(sum,(newValue,oldValue)=>{
console.log('sum变化了',newValue,oldValue)
if(sum.value>=10){
stopWatch()
}
})
function changSum(){
sum.value++
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 5px;
padding: 20px;
}
button{
margin: 0 5px;
}
</style>
浙公网安备 33010602011771号