本篇將探討關於Vue中父子元件的生命週期順序。
一、例項程式碼
父元件:
<template>
<div id="parent">
<child></child>
</div>
</template>
<script>
import child from './components/child'
export default {
name: 'parent',
components: {
child
},
beforeCreate() {
console.log('I am parents beforeCreated');
},
created() {
console.log('I am parents created');
},
beforeMount() {
console.log('I am parents beforeMount');
},
mounted() {
console.log('I am parents mounted');
}
}
</script>
複製程式碼
子元件:
<template>
<div class="child">
child
</div>
</template>
<script>
export default {
name: 'child',
beforeCreate() {
console.log('I am child beforeCreated');
},
created() {
console.log('I am child created');
},
beforeMount() {
console.log('I am child beforeMount');
},
mounted() {
console.log('I am child mounted');
}
}
</script>
複製程式碼
執行結果:
二、結論
我們從而可以得出父子元件的執行順序為:
- 父元件beforeCreated
- 父元件created
- 父元件beforeMounted
- 子元件beforeCreated
- 子元件created
- 子元件beforeMounted
- 子元件mounted
- 父元件mounted
注意:
- 父元件的mounted是在最後執行的。
- 因此在子元件的mounted中渲染父元件在mounted階段請求的資料,是會無反應的。因為子元件mounted渲染資料會發生在父元件mounted請求資料之前。