【watch】
-  作用:监视数据的变化(和 Vue2中的watch作用一致)
-  特点: Vue3中的watch只能监视以下四种数据:
ref定义的数据。
reactive定义的数据。
函数返回一个值(
getter函数)。
一个包含上述内容的数组。
我们在Vue3中使用watch的时候,通常会遇到以下几种情况 ,
在一定情况下,停止监控:stopWatch
watch(第一个参数,第二个参数) // 第一个参数是监控谁 ,第二个参数是回调函数
<template><div class="person"><h1>情况一:监视【ref】定义的【基本类型】数据</h1><h2>当前求和为:{{sum}}</h2><button @click="changeSum">点我sum+1</button></div>
</template><script lang="ts" setup name="Person">import {ref,watch} from 'vue'// 数据let sum = ref(0)// 方法function changeSum(){sum.value += 1}// 监视,情况一:监视【ref】定义的【基本类型】数据const stopWatch = watch(sum,(newValue,oldValue)=>{console.log('sum变化了',newValue,oldValue)if(newValue >= 10){stopWatch()}})
</script>