watch监听参数有三, 1、监听的对象。2、监听的回调。3、监听的配置。且必须指定监听的属性,也要指定监听的回调 watchEffect则是,不用指定监听哪个属性,而是监听的回调中用到哪个属性,那就监听哪个属性。着类似于computed:但是computed注重的计算出来的返回值,所以必须有返回值,watchEffect更注重过程(回调函数的函数体),所以不需要写返回值。 演示如下
<template>
<h2>个人信息</h2>
<p>姓名:{{ person.name }}</p>
<p>姓名:{{ person.age }}</p>
<p>工资:{{ person.job.salary.current }}</p>
<button @click="person.age++">++</button>
<button @click="person.job.salary.current++">++工资</button>
<button @click="person.name += '!'">打招呼</button>
</template>
<script>
import { reactive, watchEffect } from "vue";
export default {
setup() {
const person = reactive({
name: "张三",
age: 18,
job: {
salary: {
current: 20,
},
},
});
watchEffect(() => {
console.log("watchEffect执行");
});
return {
person,
};
},
};
</script>
打印后你会发现,默认执行了一次,也就是开启了immediate 同时我去修改数据,并没有触发watchEffect 修改代码如下
<template>
<h2>个人信息</h2>
<p>姓名:{{ person.name }}</p>
<p>姓名:{{ person.age }}</p>
<p>工资:{{ person.job.salary.current }}</p>
<button @click="person.age++">++</button>
<button @click="person.job.salary.current++">++工资</button>
<button @click="person.name += '!'">打招呼</button>
</template>
<script>
import { reactive, watchEffect } from "vue";
export default {
setup() {
const person = reactive({
name: "张三",
age: 18,
job: {
salary: {
current: 20,
},
},
});
watchEffect(() => {
const a = person.name;
const b = person.job.salary.current;
console.log("a", a);
console.log("b", b);
});
return {
person,
};
},
};
</script>
通过不断触发按钮导致数据发生改变,相应的也会触发watchEffect,并且是触发整个watchEffect
|