<template>
<!-- 用到框架中自带的vant4-->
<view>姓名:{{ name }}</view>
<van-button @click="changeName" size="small">改变姓名</van-button>
<br>
<view>年龄:{{ age }}</view>
<van-button @click="changeAge" size="small">年龄加一</van-button>
</template>
<script setup>
const name = ref('张三')
const age = ref(15)
const changeName = () =>{
name.value += '哈哈'
}
const changeAge = () =>{
age.value += 1
}
watch([name,age],(newValue)=>{
// 从 newValue 中结构对象
let [newNameValue,newAgeValue] = newValue
if(newNameValue == '张三哈哈哈哈' || newAgeValue >= 18){
alert("监听结束,执行其他操作")
}
})
</script>
监听多个对象用: (对象名)=>{} 变成函数形式再进行监听
监听多个对象的时: 直接用数组 【ref变量,ref变量】
用WatchEffect监听 更简单 ———— 立即监视 自动监视!
<script setup>
const name = ref('张三')
const age = ref(15)
const changeName = () =>{
name.value += '哈哈'
}
const changeAge = () =>{
age.value += 1
}
watchEffect(() =>{
if(name.value == '张三哈哈哈哈' || age.value >= 18){
alert("监听结束,执行其他操作")
}
})
<script>