Vue的父子组件的生命周期顺序

593 阅读1分钟

我们都知道,vue实例的生命周期依次是:

beforeCreate -> created -> beforeMount -> mounted -> ( beforeUpdate -> updated ) -> beforeDestroy -> destroyed

但当我们使用组件时,父组件和子组件的生命周期钩子的执行顺序又是怎样的呢?我们将通过代码验证:

<!-- 在父组件中使用子组件 -->
<div id="root">
   {{msg}}
   <child :message="fromParent"></child>
</div>
//子组件
Vue.component('child', {
    template:`
        <div>{{msg}}, I got {{message}}</div>
    `,
    props: ['message'],
    data(){
        return{
            msg: '我是子组件'
        }
    },
    beforeCreate () {
        console.log('child before create')
    },
    created () {
        console.log('child created')
    },
    beforeMount () {
        console.log('child before mount')
    },
    mounted () {
        console.log('child mounted')
    },
    beforeDestroy () {
        console.log('child before destroy')
    },
    destroyed () {
        console.log('child destroyed')
    },
    beforeUpdate () {
      	console.log('child before update')
    },
    updated () {
      	console.log('child updated')
    }
})
//根实例(父组件)
var vm = new Vue({
    el: '#root',
    data: {
        msg: '我是父组件'
    },
    beforeCreate () {
        console.log('parent before created')
    },
    created () {
        console.log('parent created')
    },
    beforeMount () {
        console.log('parent before mount')
    },
    mounted () {
        console.log('parent mounted')
    },
    beforeDestroy () {
        console.log('parent before destroy')
    },
    destroyed () {
        console.log('parent destroyed')
    },
    beforeUpdate () {
      	console.log('parent before update')
    },
    updated () {
      	console.log('parent updated')
    }
})

运行结果如下图:

加载渲染

组件销毁

父组件数据更新

子组件数据更新(单向数据流)

由此我们得知,父子组件的生命周期函数是嵌套的关系,从外到内,再从内到外