一、监听属性-watch
-
与vue2.x中的watch配置功能一致
-
注意
-
监视reactive定义的响应式数据时,oldvalue无法正确获取,强制开始了深度监视(deep的配置失效)
-
监视reactive定义的响应式数据的某一个值时:deep配置有效
-
1.监听ref定义的响应式数据
示例:
<script setup>
import { ref, reactive, watch } from "vue";
//监听一个数据
let msg = ref("今天星期二");
function changemsg() {
msg.value = "Today is Tuesday";
}
watch(msg, (newv, oldv) => {
console.log(newv, oldv, "msg发生了变化");
});
</script>
<template>
<div>
<p>{
{msg}}</p>
<button @click="changemsg">change-msg</button>
</div>
</template>
结果显示:
2.监听reactive定义的一个响应式数据的全部属性
示例:
<script setup>
import { reactive, watch } from "vue";
let user = reactive({name: "haha",age: 21,shopping: { cloth: 2, shooes: 1 }});
watch(user, function(newv, oldv) {
console.log("修改了name/age/shopping属性");
console.log(newv, oldv);
});
function changecloth() {
user.shopping.cloth = 3;
}
function changeshopping() {
user.shopping="no-shopping";
}
function changename() {
user.name = "xixi";
}
function changeage() {
user.age = 21;
console.log("点击了changeage按钮,修改了age,但是没有触发watch")
}
</script>
<template>
<div class="box1">
<p>{
{user}}</p>
<button @click="changecloth">changecloth</button><br /><br />
<button @click="changeshopping">changeshopping</button><br /><br />
<button @click="changename">changename</button>
<button @click="changeage">changeage</button><br /><br />
</div>
</template>
显示结果:
二、Vue3生命周期
-
什么是生命周期?
Vue中每个组件都是独立的,每个组件都有一个属于它的生命周期,从一个组件创建、数据初始化、挂载、更新、销毁、这就是一个组件所谓的生命中周期
-
Vue2.x中的生命周期
beforeCreate created
beforeMount mounted
beforeUpdate updated
beforeDestroy destroyed
activated deactivated errorCaptured
-
Vue3.x的生命周期
在Vue3.x中,新增了一个setup生命周期函数,setup执行的时机是在beforeCreate之前,因为在这个函数中不能通过this来获取实例的;同时为了命名的统一ÿ