父子孙嵌套组件的生命周期
页面一刷新父子孙的初始化生命周期:
总结:栈原理:先进后出,即父组件先创建,子组件先挂载。
看例子:
<template><div class="Dome1"><div>Dome1</div><button @click="onClose">{{ isShow ? '关闭' : '打开' }}</button><Dome2 v-if="isShow" :url="url" /></div>
</template><script>
import Dome2 from "./dome2.vue";
export default {name: 'TestOne',data () {return {name: 'Dome1',isShow: true,}},components: { Dome2 },beforeCreate () {
// data里面的数据是undefinedconsole.log('创建前->beforeCreate->Dome1');},created () {console.log('创建->created->Dome1');},beforeMount () {console.log('挂载前->beforeMount->Dome1');},mounted () {console.log('挂载->mounted->Dome1');},beforeUpdate () {console.log('更新前->beforeUpdate->Dome1');},updated () {
// watch computed 等在这个时候更新console.log('更新->updated->Dome1');},beforeUnmount () {console.log('销毁前->beforeUnmount->Dome1');},unmounted () {console.log('销毁->unmounted->Dome1');},methods: {onClose () {this.isShow = !this.isShow}}
}
</script><style scoped>
.Dome1 {margin: 0 auto;width: 1000px;height: 800px;background-color: rosybrown;display: flex;justify-content: center;align-items: center;
}
</style>
<template><div class="Dome2"><div>Dome2</div><Dome3 /></div>
</template><script>
import Dome3 from "./dome3.vue";export default {name: 'TestTwo',data () {return {}},props: ['url'],components: { Dome3 },beforeCreate () {console.log('创建前->beforeCreate->Dome2');},created () {console.log('创建->created->Dome2');},beforeMount () {console.log('挂载前->beforeMount->Dome2');},mounted () {console.log('挂载->mounted->Dome2');},beforeUpdate () {console.log('更新前->beforeUpdate->Dome2');},updated () {console.log('更新->updated->Dome2');},beforeUnmount () {console.log('销毁前->beforeUnmount->Dome2');},unmounted () {console.log('销毁->unmounted->Dome2');}
}
</script><style scoped>
.Dome2 {width: 800px;height: 400px;background-color: lightgreen;display: flex;justify-content: center;
}
</style>
<template><div class="Dome3">Dome3</div>
</template><script>
export default {name: 'TestThree',data () {return {}},beforeCreate () {console.log('创建前->beforeCreate->Dome3');},created () {console.log('创建->created->Dome3');},beforeUpdate () {console.log('更新前->beforeUpdate->Dome3');},updated () {console.log('更新->updated->Dome3');},beforeMount () {console.log('挂载前->beforeMount->Dome3');},mounted () {console.log('挂载->mounted->Dome3');},beforeUnmount () {console.log('销毁前->beforeUnmount->Dome3');},unmounted () {console.log('销毁->unmounted->Dome3');}
}
</script><style scoped>
.Dome3 {width: 200px;height: 200px;background-color: red;margin: 80px auto;
}
</style>
当点击Dome2关闭时,更新销毁函数
总结:销毁是“从外向内”,父组件最先进入销毁,孙组件先销毁。
当所有组件要被销毁的时候是销毁顺序是从父到子,再到孙;父组件最先进入销毁阶段,孙组件最后销毁