1.vue的生命周期
2.views/createrCustormer.vue為父級
<template>
<expressService />
</template>
<script> import expressService from '@/components/expressService' export default { components: { expressService }, beforeCreate() { const time = (new Date()).getTime() console.group('beforeCreate父級 實例初始化進行數據觀測/事件配置', time) }, created() { const time = (new Date()).getTime() console.log('created父級 實例創建完成', time) }, beforeMount() { const time = (new Date()).getTime() console.group('beforeMount父級 掛載開始', time) }, mounted() { const time = (new Date()).getTime() console.log('mounted父級 掛載到實例上', time) }, beforeUpdate() { const time = (new Date()).getTime() console.group('beforeUpdate父級 數據更新前', time) }, updated() { const time = (new Date()).getTime() console.log('updated父級 組件DOM更新', time) }, beforeDestroy() { const time = (new Date()).getTime() console.log('updated父級', time) console.group('beforeDestroy父級 實例銷毀前', time) }, destroyed() { const time = (new Date()).getTime() console.log('destroyed父級 實例銷毀完成', time) } }
</script>
3.components/expressService.vue
<template> <div class="expressService"> 子級生命周期 </div> </template> <script> export default { beforeCreate() { const time = (new Date()).getTime() console.group('beforeCreate子級', time) }, created() { const time = (new Date()).getTime() console.log('created子級', time) }, beforeMount() { const time = (new Date()).getTime() console.group('beforeMount子級', time) }, mounted() { const time = (new Date()).getTime() console.log('mounted子級', time) }, beforeUpdate() { const time = (new Date()).getTime() console.group('beforeUpdate子級', time) }, updated() { const time = (new Date()).getTime() console.log('updated子級', time) }, beforeDestroy() { const time = (new Date()).getTime() console.group('beforeDestroy子級', time) }, destroyed() { const time = (new Date()).getTime() console.log('destroyed子級', time) } } </script>
4.打印看一下什么情況
從打印我們可以看出來,父級beforeMount掛載開始時才會進入到子級beforeCreate實例化開始,但是子級mounted掛載實例比父級mounted掛載實例要快1毫秒,為什么呢?並且子級初次渲染時沒有數據更新,那什么時候子級會數據更新呢?
5.子級mounted掛載實例比父級mounted掛載實例要快1毫秒
當父組件執行完beforeMount掛載開始后,會依次執行子組件中的鈎子,直到全部子組件mounted掛載到實例上,父組件才會進入mounted鈎子
6.子級數據更新
當對子級進行事件處理時,就會觸發哦,從下圖可以看出,子級進行事件,會先觸發父級beforeUpdate鈎子,再去觸發子級beforeUpdate鈎子,下面又是先執行子級updated鈎子,后執行父級updated鈎子,同理與5相同
7.心得
這個問題之前在面試的時候被提到過很多遍,主要考的是對vue原理的深度了解的有多少,面試真的是一個了解當下前端趨勢的一個很好的方法,面試中會遇到各種在工作中沒有遇到過的問題,第一次不懂沒關系,以后慢慢懂就好啦!歡迎大神來糾正bug,哈哈哈