今天在学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
}
}
});
watch(()=>person.name,(newValue,oldValue)=>{
console.log('person的值改变了',newValue,oldValue);
})
watch([()=>person.name,()=>person.age],(newValue,oldValue)=>{
console.log('person的值改变了',newValue,oldValue);
})
watch(()=>person.job,(newValue,oldValue)=>{
console.log('person的值改变了',newValue,oldValue);
},{deep:true})
return {
sum,
msg,
person,
};
},
};
</script>
<style>
</style>