Father.vue:
<script> import Child from './Child' export default { beforeCreate() { console.log('父組件 beforeCreate') }, created() { console.log('父組件 created') }, render() { console.log('父組件 render') return ( <div> <h1>父組件</h1> <Child /> </div> ) }, beforeMount() { console.log('父組件 beforeMount') }, mounted() { console.log('父組件 mounted') }, components: { Child } } </script> <style> div { text-align: center; } </style>
Child.vue:
<script> export default { beforeCreate() { console.log('子組件 beforeCreate') }, created() { console.log('子組件 created') }, render() { console.log('子組件 render') return ( <div> <h3>子組件</h3> </div> ) }, beforeMount() { console.log('子組件 beforeMount') }, mounted() { console.log('子組件 mounted') } } </script>
結果:父組件初始化 -> 父組件渲染完畢 -> 子組件初始化 -> 子組件掛載完畢 -> 父組件掛載完畢
子組件何時知道父組件已經掛載?
main.js:
Vue.prototype.$bus = new Vue()
Father.vue:
mounted() { console.log('父組件 mounted') this.$bus.$emit('fatherMounted') }
Child.vue:
mounted() { console.log('子組件 mounted') this.$bus.$on('fatherMounted', () => { console.log('父組件已掛載') }) }