我们都知道Vue2中八大 生命周期钩子
第一部分-初始化相关属性
beforeCreate created beforeMount mounted
第二部分-更新数据
beforeUpdate updated
第三部分-销毁相关属性
beforeDestroy destroyed
当我们结合父子组件使用时
父组件中
<template>
<div class="father" v-if="IsDisplay">
<h2>父组件- {{num}} </h2>
<button @click="num++">更新</button>
<button @click="IsDisplay = false">隐藏</button>
<static2Child :num ='num' ></static2Child>
</div>
</template>
<script>
import static2Child from '@/views/staticRoutes/static2Child'
export default {
name: "Vue2TestStatic2",
// 注册组件
components:{
static2Child,
},
data() {
return {
num: 0,
IsDisplay: true,
};
},
beforeCreate() {
console.log("父beforeCreate");
},
created() {
console.log("父create");
},
beforeMount() {
console.log("父beforeMount");
},
mounted() {
console.log("父mounted");
},
beforeUpdate() {
console.log("父beforeUpdate");
},
updated() {
console.log("父updated");
},
beforeDestroy() {
console.log("父beforeDestroy");
},
destroyed() {
console.log("父destroyed");
},
};
</script>
<style lang="scss" scoped>
.father{
width: 500px;
height: 300px;
border: 1px solid black;
}
</style>
子组件中
<template>
<div class="son">
我是子组件-{{ num }}
</div>
</template>
<script>
export default {
name: "Vue2TestStatic2Child",
props: {
num: {
type: Number,
default: 0,
},
},
beforeCreate() {
console.log("子beforeCreate");
},
created() {
console.log("子create");
},
beforeMount() {
console.log("子beforeMount");
},
mounted() {
console.log("子mounted");
},
beforeUpdate() {
console.log("子beforeUpdate");
},
updated() {
console.log("子updated");
},
beforeDestroy() {
console.log("子beforeDestroy");
},
destroyed() {
console.log("子destroyed");
},
};
</script>
<style lang="scss" scoped>
.son {
width: 200px;
height: 50px;
border: 1px solid pink;
}
</style>
挂载阶段
更新阶段
销毁阶段 (存在问题 没有让父组件‘自己销毁’ 显示父组件在更新)
结论
父beforeCreate -> 父created -> 父beforeMount -> 子beforeCreate -> 子created -> 子beforeMount -> 子mounted -> 父mounted->父beforeUpdate->子beforeUpdate->子updated->父updated->父beforeDestroy->子beforeDestroy->子destroyed->父destroyed