今天在学vue3时,学到watch时,发现相对于vue2,vue3的watch有很多注意点,所以记录下来:
<template>
<h1>我是Demo组件</h1>
<h2>当前求和为:{
{
sum }}</h2>
<button @click="sum++">点击+1</button>
<br />
<h2>当前的信息是是:{
{
msg }}</h2>
<button @click="msg += '!'">点击+!</button>
<br />
<h2>姓名:{
{
person.name }}</h2>
<h2>年龄:{
{
person.age }}</h2>
<h2>第一份工资的薪水:{
{
person.job.j1.salary }}</h2>
<button @click="person.name += '#'">修改姓名</button>
<button @click="person.age++">年龄+1</button>
<button @click="person.job.j1.salary++">涨薪+1</button>
</template>
<script>
import {
ref, reactive, watch } from "vue";
export default {
name: "App",
setup() {
let sum = ref(0);
let msg = ref("nihao");
let person = reactive({
name: "张三",
age: 18,
job:{
j1:{
salary:20
}
}
});
//情况一:监视ref所定义的一个响应式数据 watch(监视的属性,回调函数,配置项)
// watch(sum,(newValue,oldValue)=>{
// console.log('sun的值改变了',newValue,oldValue);
// },{immediate:true})
//情况二:监视ref所定义的多个响应式数据
// watch([sum, msg], (newValue, oldValue) => {
// console.log("sum或msg的值改变了", newValue, oldValue);
// });
/**
*情况三:监视 reactive 所定义的一个响应式数据的所有属性
问题一 :oldValue的值等于newValue
问题一 :关闭深度监视后(deep:false),修改 person.job.j1.salary 仍会触发监视
*/
// watch(person,(newValue,oldValue)=>{
// console.log('person的值改变了',newValue,oldValue);
// },{immediate:true,deep:false})
//情况四:监视 reactive 所定义的一个响应式数据的某个属性
watch(()=>person.name,(newValue,oldValue)=>{
console.log('person的值改变了',newValue,oldValue);
})
//情况五:监视 reactive 所定义的一个响应式数据的某些属性
watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{
console.log('person的值改变了',newValue,oldValue);
})
//情况六:监视 reactive 所定义的一个响应式数据的对象 oldValue的值依旧等于newValue
watch(()=>person.job,(newValue,oldValue)=>{
console.log('person的值改变了',newValue,oldValue);
},{
deep:true}) //此处要开启深度监视
return {
sum,
msg,
person,
};
},
};
</script>
<style>
</style>