1.watch的多种情况
let sum =ref(0)
let msg=ref('你好啊')
let person=ref({
name:'张三',
job:'前端工程师'
})
//情况一:监视ref所定义的一个响应式数据
watch(sum,(newValue,oldValue)=>{
console.log('sum变了',newValue,oldValue)
},{immediate:true})
//情况二:监视ref所定义的多个响应式数据
watch([sum,msg],(newValue,oldValue)=>{
console.log('sum或msg变了',newValue,oldValue)
},{immediate:true})
//情况三:监视reactive所定义的一个响应式数据的全部属性
watch(person,(newValue,oldValue)=>{
console.log('person变化了',newValue,oldValue)
},{deep:false}) //此处的deep配置无效
//情况四:监视reactive所定义的一个响应式数据中的某个属性
watch(()=>person.name,(newValue,oldValue)=>{
console.log('person的name变化了',newValue,oldValue)
})
//情况五:监视reactive所定义的一个响应式数据中的某些属性
watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{
console.log('person的name或age变化了',newValue,oldValue)
})
//特殊情况
watch(()=>person.job,(newValue,oldValue)=>{
console.log('person的job变化了',newValue,oldValue)
},{deep:true}) //此处由于监视的是reactive素定义的对象中的某个属性,所以deep配置有效 */
注意: deep:true是深度监听 开启后能够复杂的结构对象或数组 immediate:true是一开始就监听
2.wacthEffect监听
<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>
wacthEffect默认immediate:true
<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>
在wacthEffect里 谁用到了 就会监听谁
computed注重计算出来的结果(回调函数的返回值),所以必须要写返回值
wacthEffect更注重过程(回调函数的函数体),所以返回值不是必须的