Watch的使用
watch的API完全等同于组件watch选项的Property:
- watch需要侦听特定的数据源,并在回调函数中执行副作用;
- 默认情况下它是惰性的,只有当被侦听的源发生变化时才会执行回调(也就是说,当页面初次渲染的时候,不会执行回调);
与watchEffect的比较,watch允许我们:
- 懒执行副作用(页面第一次渲染的时候不会直接执行回调);
- 更具体的说明当哪些状态发生变化时,触发侦听器的执行;
- 访问侦听状态变化前后的值;
watch侦听函数的数据源有两种类型:
- 一个getter函数:但是该getter函数必须引用可响应式的对象(比如reactive或者ref或者props);
- 直接写入一个可响应式的对象,reactive或者ref(比较常用的是ref);
watch可以侦听单个数据源
,也可以侦听多个数据源
侦听单个数据源
watch侦听单个数据源,数据源的类型可以是:
- 一个getter函数:但是该getter函数必须引用可响应式的对象(比如reactive或者ref或者props);
- 可响应式对象,reactive对象或ref对象,一般多使用ref对象
1.数据源为getter函数
watch监听的数据源如果为getter函数,此函数中必须有对可响应式对象的引用
<template>
<div>
<div>student名字:{{ student.name }}, 年龄: {{ student.age }}</div>
<div>info班级:{{ info.class }}, 分数: {{ info.score }}</div>
<div>friend姓名:{{ friend.name }}, 性别: {{ friend.sex }}</div>
<button @click="changeStudentName">修改student名字</button>
<button @click="changeInfoScore">修改info分数</button>
<button @click="changeFriendName">修改friend分数</button>
</div>
</template>
<script>
import { ref, reactive, watch } from "vue";
export default {
setup() {
const student = reactive({ name: "why", age: 18 });
const info = ref({ class: "六一", score: 98 });
const friend = { name: "李红", sex: "女" };
//监听可响应式对象reactive的某个属性的改变
watch(
() => student.name,
(newVal, oldVal) => {
console.log("newName:", newVal, "oldName:", oldVal);
}
);
//监听可响应式对象ref的某个属性的改变
watch(
() => info.value.score,
(newVal, oldVal) => {
console.log("newScore:", newVal, "oldScore:", oldVal);
}
);
//监听普通对象的某个属性的改变:watch无法监听普通对象属性的改变
watch(
() => friend.name,
(newVal, oldVal) => {
console.log("newFriendName:", newVal, "oldFriendName:", oldVal);
},
{
deep: true,
}
);
const changeStudentName = () => {
student.name = "koby";
};
const changeInfoScore = () => {
info.value.score = 80;
};
const changeFriendName = () => {
friend.name = "小雨";
console.log(111, friend.name)
};
return {
student,
info,
friend,
changeStudentName,
changeInfoScore,
changeFriendName,
};
},
};
</script>
<style lang="scss" scoped></style>
image.png
friend为一个普通对象,watch是监听不到的
2.数据为可响应式对象reactive对象或ref对象或props对象的某个属性
<template>
<div>
<h1>{{ title }}</h1>
<div>名字:{{ info.name }}, 年龄: {{ info.age }}</div>
<button @click="changeName">修改名字</button>
<button @click="changeTitle">修改标题</button>
</div>
</template>
<script>
import { ref, reactive, watch } from "vue";
export default {
setup() {
const info = reactive({ name: "why", age: 18 });
const title = ref("hello world");
//1.监听目标为一个可响应式对象:reactive/ref对象
//如果是reactive,newVal和oldVal都为reactive对象
//如果是ref对象,newVal和oldVal为ref对象的value的值
watch(info, (newVal, oldVal) => {
console.log("newVal:", newVal, "oldVal:", oldVal);
});
watch(title, (newVal, oldVal) => {
console.log('newVal:', newVal, 'oldVal:', oldVal)
})
//2.监听数据源为reactive对象时,如果想oldVal和newVal是一个普通对象,把其写法一个返回普通对象的getter函数
watch(() => ({...info}), (newVal, oldVal) => {
console.log('newVal:', newVal, 'oldVal:', oldVal)
})
const changeName = () => {
info.name = "koby";
};
const changeTitle = () => {
title.value = "今天天气不错";
};
return {
info,
title,
changeName,
changeTitle,
};
},
};
</script>
<style lang="scss" scoped></style>
image.png
3.watch监听props对象的某个属性
props对象本身也是一个响应式对象,监听可响应式对象的属性,需要把其转换为getter函数
App.vue
<template>
<div>
<my-home :info="info" />
<button @click="changeInfo">修改info</button>
</div>
</template>
<script>
import { ref, reactive, watch } from "vue";
import MyHome from "./Home.vue";
export default {
components: {
MyHome,
},
setup() {
const info = reactive({
name: "why",
age: 18,
friend: { name: "koby" },
});
const changeInfo = () => {
info.friend.name = "lily";
};
return {
info,
changeInfo,
};
},
};
</script>
<style lang="scss" scoped></style>
Home.vue
<template>
<div>
<div>home名字:{{ info.name }}, 年龄: {{ info.age }}</div>
</div>
</template>
<script>
import { ref, reactive, watch } from "vue";
export default {
props: {
info: {
type: Object,
required: true,
},
},
setup(props) {
watch(
() => props.info,
(newVal, oldVal) => {
console.log("newVal:", newVal, "oldVal:", oldVal);
},
{
deep: true,
}
);
return {};
},
};
</script>
<style lang="scss" scoped></style>
image.png
侦听多个数据源
<template>
<div>
<h1>{{ title }}</h1>
<div>名字:{{ info.name }}, 年龄: {{ info.age }}</div>
<button @click="changeName">修改名字</button>
<button @click="changeTitle">修改标题</button>
</div>
</template>
<script>
import { ref, reactive, watch } from "vue";
export default {
setup() {
const info = reactive({ name: "why", age: 18 });
let title = ref("hello world");
//监听目标为一个数组:监听多个数据源
watch([info, title], ([newInfo, newTitle], [oldInfo, oldTitle]) => {
console.log("newInfo:", newInfo, "oldInfo:", oldInfo);
console.log("newTitle:", newTitle, "oldTitle:", oldTitle);
});
//如果希望newInfo, oldInfo不是reactive对象,是普通对象
watch(
[() => ({ ...info }), title],
([newInfo, newTitle], [oldInfo, oldTitle]) => {
console.log("newInfo:", newInfo, "oldInfo:", oldInfo);
console.log("newTitle:", newTitle, "oldTitle:", oldTitle);
}
);
const changeName = () => {
info.name = "koby";
};
const changeTitle = () => {
title.value = "今天天气不错";
};
return {
info,
title,
changeName,
changeTitle,
};
},
};
</script>
<style lang="scss" scoped></style>
image.png
watch的选项
如果我们希望侦听一个深层的侦听,那么依然需要设置 deep 为true:
也可以传入 immediate 立即执行;
watch的深度监听
<template>
<div>
<div>名字:{{ info.name }}, 年龄: {{ info.age }}</div>
<button @click="changeName">修改名字</button>
<button @click="changeStudent">修改studnet同桌名字</button>
</div>
</template>
<script>
import { ref, reactive, watch } from "vue";
export default {
setup() {
const info = reactive({
name: "why",
age: 18,
friend: { name: "koby" },
});
const student = ref({
class: "六一",
score: 98,
deskmate: { name: "lily" },
});
//1.监听目标为reactive对象,默认是深度侦听的
watch(info, (newVal, oldVal) => {
console.log("newVal:", newVal, "oldVal:", oldVal);
});
//2.监听目标为ref对象, 默认不是深度监听,需要手动开启手动监听
watch(
student,
(newVal, oldVal) => {
console.log("newStudent:", newVal, "oldStudent:", oldVal);
},
{
deep: true, //开启深度侦听
}
);
//2.监听目标为普通对象,不是深度侦听的,需要手动开启深度监听
watch(
() => ({ ...info }),
(newVal, oldVal) => {
console.log("newVal:", newVal, "oldVal:", oldVal);
},
{
deep: true, //开启深度侦听
immediate: true, //首次渲染说的时候,也监听一次
}
);
const changeName = () => {
info.friend.name = "curry";
};
const changeStudent = () => {
student.value.deskmate.name = "jack";
};
return {
info,
changeName,
changeStudent,
};
},
};
</script>
<style lang="scss" scoped></style>
image.png
此文档主要内容来源于王红元老师的vue3+ts视频教程