1.使用之前导入
import { ref, reactive, watch, watchEffect } from "vue";
2.watch与watchEffect定义
watch(侦听的响应式引用,回调函数)
,接收两个参数,第一个是需要监听的对象,第二个是处理函数
watchEffect(回调函数)
,只接收一个参数,不需要指定监听的属性
在vue3中,均主要用于监听ref
和reactive
数据的变化
3.watch与watchEffect使用
//定义counter及相关函数
const counter = ref(0);
function changeCounter() {
counter.value++;
}
//watch(侦听的响应式引用,回调函数)
watch(counter, (newVal, oldVal) => {
console.log("newVal--->", newVal);
console.log("oldVal--->", oldVal);
});
//定义user及相关函数
const user = reactive({
name: "张三",
age: 18,
});
function changeUserName() {
user.name = "李四";
}
watch(user.name, (newVal, oldVal) => {
console.log("newVal--->", newVal);
console.log("oldVal--->", oldVal);
}); //不能监听到reactive定义的对象的属性,警告:张三 A watch source can only be a getter/effect function, a ref, a reactive object, or an array of these types.
watch(
() => user.name,
(newVal, oldVal) => {
console.log("newVal--->", newVal);
console.log("oldVal--->", oldVal);
}
);//监听对象的属性时,需要使用函数的形式才能正确返回
watchEffect(() => {
console.log(user.name);
});// watchEffect(回调函数),注意:不需要指定监听的属性,组件初始化的时候会执行一次回调函数,会自动收集依赖,但无法获取上一次的值
<div>
<h2>{{ counter }}</h2>
<button @click="changeCounter">改变counter</button>
<h2>{{ user.name }}</h2>
<button @click="changeUserName">改变name</button>
</div>
4.watch和watchEffect区别:
- 1.watchEffect不需要指定监听属性,自动收集依赖,
只要在回调中引用到了响应式的属性,只要这些属性发生改变,回调就会执行
,watch只能监听指定的属性
- 2.watch可以获取到新值和旧值,watchEffect无法获取上一次的值
- 3.watchEffect在
组件初始化
的时候就会自动执行一次
,用来收集依赖
,而watch是惰性
的,在第一次加载时不会执行处理函数