vue3 监视属性

<template>
    <h3>Vue3的监视属性</h3>
    <p>我是Watch组件</p>
    <div>
        <h4>情况一:监视基本数据类型</h4>
        当前求和为:{{ sum }}
        <button @click="changeSum">点我+1</button>
    </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
const sum = ref(0)
const changeSum = () => {
    sum.value += 1
}

/* 
    watch(要被监视的属性,监视后的回调 函数    
    stopWatch名称无所谓,可以任意起名
    stopWatch代表的是每次监视完毕后的回调值
    加上()形成stopWatch() 代表停止监视
*/
const stopWatch = watch(sum, (newValue, oldValue) => {
    console.log('sum变化了,watch监视属性生效')
    console.log('变化后:' + newValue, '变化前:' + oldValue)
    // 当变化后的值大于5后,停止对sum属性的监视
    if (newValue > 5) {
        stopWatch();
    }
    console.log(newValue)
})
</script>
posted @ 2024-02-24 09:21  Anbin啊  阅读(2)  评论(0)    收藏  举报