上一篇:vue3 watchEffect函数https://blog.csdn.net/qq_42543244/article/details/122291727
记录vue3的生命周期,于vue2相比,变化并不算很大,最大的变化是,组合式的开发,意味着如果需要在某个生命周期中写点代码,那么前提是必须引入,然后叫法单词上发生的一些变化,先看官网给出的周期图:
vue2:
vue3:
然后有两种写法,为了能更好的呈现出来,我就直接贴代码了:
父组件(因为生命周期中有卸载前,已卸载的周期函数,所以我在父组件中进行了v-if的切换)
<template>
<button @click="isShow = !isShow">点击切换隐藏/显示</button>
<demo v-if="isShow"></demo>
</template>
<script>
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
} from "vue";
import Demo from "@/components/Demo.vue";
export default {
name: "App",
components: {
Demo,
},
setup() {
let isShow = ref(true);
console.log("----parent-setup----");
onBeforeMount(() => {
console.log("----parent-onBeforeMount----");
});
onMounted(() => {
console.log("----parent-onMounted----");
});
onBeforeUpdate(() => {
console.log("----parent-onBeforeUpdate----");
});
onUpdated(() => {
console.log("----parent-onUpdated----");
});
onBeforeUnmount(() => {
console.log("----parent-onBeforeUnmount----");
});
onUnmounted(() => {
console.log("----parent-onUnmounted----");
});
return { isShow };
},
};
</script>
子组件(Demo.vue)
<template>
<div>Demo组件内容</div>
<div>{{ num }}</div>
<button @click="num++">点击+1</button>
</template>
<script>
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
} from "vue";
export default {
name: "Demo",
/*
vue3 的生命周期和 vue2的很相似,基本保持一致,最后的 destory 改成了 unmount
使用方法有两种,一种是声明式的,即写在setup外面 与setup同级
一种是组合式的,需要先进行引入 ,,根据个人喜好选择一种即可,也可以全写,但需要注意执行顺序
*/
/* beforeCreate() {
console.log("----beforeCreate----");
},
created() {
console.log("----created----");
},
beforeMount() {
console.log("----beforeMount----");
},
mounted() {
console.log("----mounted----");
},
beforeUpdate() {
console.log("----beforeUpdate----");
},
updated() {
console.log("----updated----");
},
beforeUnmount() {
console.log("----beforeUnmount----");
},
unmounted() {
console.log("----unmounted----");
}, */
setup() {
/* 在setup中使用组合式api,生命周期函数需要事先引入,组合式内的生命周期执行顺序是要快于声明式的生命周期
组合式的引入是没有 onBeforeCreate,onCreated的,认为setup即为beforeCreate,created
*/
let num = ref(1);
console.log("----children-setup----");
onBeforeMount(() => {
console.log("----children-onBeforeMount----");
});
onMounted(() => {
console.log("----children-onMounted----");
});
onBeforeUpdate(() => {
console.log("----children-onBeforeUpdate----");
});
onUpdated(() => {
console.log("----children-onUpdated----");
});
onBeforeUnmount(() => {
console.log("----children-onBeforeUnmount----");
});
onUnmounted(() => {
console.log("----children-onUnmounted----");
});
return { num };
},
};
</script>
大概就是这些,演示下,父子组件的渲染顺序
(父组件setup --- > 父组件挂载前 ---> 子组件setup--->子组件挂载前--->子组件挂载后--->父组件键挂载后)
就到这里吧!
下一篇:
vue3 自定义hook函数https://blog.csdn.net/qq_42543244/article/details/122644055