watch
Vue3中的watch只能监视以下4种数据:
ref
定义的数据reactive
定义的数据- 函数返回一个值(
getter
函数) - 一个包含上述内容的数组
1.监听基本类型数据
watch可以监视变量的变化并基于该变化做出响应,也可以关闭此侦听器,注意,你不能监听变量的属性值
<template>
<div>{{ num }}</div>
<button @click="num++">add</button>
</template>
<script setup name="App">
import { ref, watch } from "vue";
let num=ref(0)
const stopWatch=watch(num,(newValue,oldValue)=>{
console.log('num变化了',newValue,oldValue);
if(newValue>=10){
stopWatch()
}
})
</script>
<style scoped></style>
2.监听对象类型数据
<template>
<div>{{ obj1.num }}</div>
<button @click="obj1.num++">add</button>
<button @click="changec1">修改c1</button>
</template>
<script setup name="App">
import { ref,reactive, watch, } from "vue";
let obj1=reactive({
num:0,
car:{
c1:'奔驰',
c2:'宝马'
}
})
function changec1() {
obj1.car.c1='兰博基尼'
}
// 监视整个对象:ref或reactive
// ref需要深度监视对象的属性值需要deep:true,reactive则不需要,它默认是deep:true
// 加上immediate可以在挂载前就执行一次watch
watch(obj1,(newValue,oldValue)=>{
console.log('obj变化了',newValue,oldValue);
},{deep:true,immediate:true})
// 监视对象的某个属性:基本类型需要写成getter函数,对象类型则不需要,只能用reactive
watch(()=>obj1.num,(newValue,oldValue)=>{
console.log('obj.num变化了',newValue,oldValue);
})
watch(obj1.car,(newValue,oldValue)=>{
console.log('obj.car变化了',newValue,oldValue);
})
</script>
<style scoped></style>
3.监听多个数据
一般使用数组监听多个数据
<template>
<div>{{ obj1.num }}</div>
<button @click="obj1.num++">add</button>
<button @click="changec1">修改c1</button>
</template>
<script setup name="App">
import { ref,reactive, watch, } from "vue";
let obj1=reactive({
num:0,
car:{
c1:'奔驰',
c2:'宝马'
}
})
function changec1() {
obj1.car.c1='兰博基尼'
}
watch([()=>obj1.num,obj1.car],(newValue,oldValue)=>{
console.log('obj变化了',newValue,oldValue);
})
</script>
<style scoped></style>
4.watchEffect
watchEffect不需要指定监听哪个数据
<template>
<div>{{ obj1.num }}</div>
<button @click="obj1.num++">add</button>
</template>
<script setup name="App">
import { ref,reactive, watchEffect, } from "vue";
let obj1=reactive({num:0})
watchEffect(()=>{
if (obj1.num>=5) {
console.log('响应');
}
})
</script>
<style scoped></style>