在Vue中,每个组件都有其对应的生命周期,这个过程与Vue 生命周期中描述的过程一致。
Vue组件的生命周期图示如下:
下图是尚硅谷天禹所给的有关Vue生命周期的解释:
嵌套组件的生命周期
定义存在嵌套关系的组件:
App.vue
(父组件,3秒后自动销毁):
<template>
<div>
<h1>App.vue</h1>
<UserInfo/>
</div>
</template>
<script>
import SubComponent from './components/SubComponent.vue';
export default {
name: 'app',
components: {SubComponent},
beforeCreate() {
console.log('App beforeCreate...');
},
created() {
console.log('App created...');
},
beforeMount() {
console.log('App beforeMount...');
},
mounted() {
console.log('App mounted...');
// 3秒后自动销毁
setTimeout(() => {
this.$destroy()
}, 3000);
},
beforeDestroy() {
console.log('App beforeDestroy...');
},
destroyed() {
console.log('App destroyed...');
},
}
</script>
SubComponent.vue
(子组件,不自动销毁):
<template>
<h2>SubComponent.vue</h2>
</template>
<script>
export default {
name: 'SubComponent',
beforeCreate() {
console.log('SubComponent beforeCreate...');
},
created() {
console.log('SubComponent created...');
},
beforeMount() {
console.log('SubComponent beforeMount...');
},
mounted() {
console.log('SubComponent mounted...');
},
beforeDestroy() {
console.log('SubComponent beforeDestroy...');
},
destroyed() {
console.log('SubComponent destroyed...');
},
}
</script>
启动项目后,浏览器控制台输出内容如下:
App beforeCreate...
App created...
App beforeMount...
SubComponent beforeCreate...
SubComponent created...
SubComponent beforeMount...
SubComponent mounted...
App mounted...
App beforeDestroy...
SubComponent beforeDestroy...
SubComponent destroyed...
App destroyed...
从控制台的输出中可以看出,子组件的初始化及挂载流程(从beforeCreate
到mounted
)是在父组件挂载流程(从beforeMount
到mounted
)中完成的;子组件的销毁流程(从beforeDestroy
到destroyed
)是在父组件的卸载流程(从beforeDestroy
到destroyed
)中完成的。
嵌套的组件的生命周期可以用下图来表示:
评论