watch监听器
用于监听响应式变量,当传入的响应式变量发生变化就执行传入的逻辑,用法如下:
vue
12345678910111213141516
<template>
<input type="text" v-model="name1" />
<input type="text" v-model="name2" />
</template>
<script setup>
import { ref, watch } from "vue";
const name1 = ref("张三");
const name2 = ref("李四");
//当有多个变量需要监听时,可以使用数组,这样返回的值也是一个数组
watch([name1, name2], (newValues, oldValues) => {
console.log(newValues, oldValues);
});
</script>
watch的其他参数
js
1234567891011121314151617
import { ref, watch } from "vue";
const name1 = ref({
foo:{
bar:{
name:"Cain"
}
}
});
watch(name1, (newValues, oldValues) => {
console.log(newValues, oldValues);
},{
deep:true,//开启深度监听
immediate:true,//立即执行
flush:"pre"//pre 组件更新前执行 sync 同步执行 post 组件更新后执行
});