Vue3-WatchEffect
watchEffect函数的使用
watchEffect函数
- 自动监听回调函数里使用到的 响应式对象
- 不用指明监听的对象,回调使用到哪个对象就监听哪个对象
与watch监听对比
- 既要指明监视的属性,也要指明回调函数
与computed计算属性对比
- computed注重结果,也就是返回值
- watchEffect注重逻辑,也就是回调执行的过程(报销流程,axios请求等)
<template>
<button @click="sum++">点我加1</button>
<button @click="person.job.job1.salary += 1">涨薪</button>
</template>
<script>
import { ref, reactive, watchEffect } from "vue";
export default {
name: "Demo",
setup() {
// 数据
let sum = ref(0);
let msg = ref("你好啊");
let person = reactive({
name: "张三",
age: 18,
job: {
job1: {
salary: 20,
},
},
});
watchEffect(() => {
const x1 = sum.value;
const x2 = person.job.job1.salary;
console.log("watchEffect的回调执行了");
})
}
}
</script>