watch 需要侦听特定的数据源,并在单独的回调函数中执行副作用
- watch第一个参数监听源,监听多个ref 注意变成数组啦
- watch第二个参数回调函数cb(newVal,oldVal)
- watch第三个参数一个options配置项是一个对象
{
immediate: true //是否立即调用一次
deep: true //是否开启深度监听
}
immediate: true 是否立即调用一次
<script setup lang="ts">
import { watch, ref } from "vue";
let msg = ref("小雪");
let msg1 = ref("小满");
watch(
[msg, msg1],
(newVale, oldVal) => {
console.log("新", newVale);
console.log("旧", oldVal);
},
{
immediate: true,
}
);
</script>
<template>
<input type="text" v-model="msg" />
<input type="text" v-model="msg1" />
</template>
deep:true是否开启深度监听
<script setup lang="ts">
import { watch, ref } from "vue";
let msg = ref({
nav:{
bar:{
name:"小雪"
}
}
});
watch(
msg,
(newVale, oldVal) => {
console.log("新", newVale);
console.log("旧", oldVal);
}
);
</script>
<template>
<input type="text" v-model="msg.nav.bar.name" />
</template>
<style></style>
没有任何打印结果,加了deep:true以后:
这是Vue的一个Bug,新值旧值一样
监听Reactive
使用reactive监听深层对象开启和不开启deep 效果一样
<script setup lang="ts">
import { watch, ref,reactive } from "vue";
let msg = reactive({
nav:{
bar:{
name:"小雪"
}
}
});
watch(
msg,
(newVale, oldVal) => {
console.log("新", newVale);
console.log("旧", oldVal);
}
);
</script>
<template>
<input type="text" v-model="msg.nav.bar.name" />
</template>
监听reactive 单一值
<script setup lang="ts">
import { watch, ref, reactive } from "vue";
let msg = reactive({
name1: "小雪",
name2: "小兰",
});
watch(
() => msg.name1,
(newVale, oldVal) => {
console.log("新", newVale);
console.log("旧", oldVal);
}
);
</script>
<template>
<input type="text" v-model="msg.name1" />
<input type="text" v-model="msg.name2" />
</template>
用reactive可以不写deep也能监听到