vue2父子组件生命周期的执行顺序网上有些不一致,实践得到结论

223 阅读1分钟

一 、父组件和子组件 创建时候的渲染过程

父 beforeCreate ——> 父 Created -> 父 beforeMount -> 子 beforeCreate -> 子 Create ->子 beforeMount -> 子 mounted -> 父 mounted

二 、父组件和子组件 子组件更新的时候

父dady beforeUpdate -> 子child beforeUpdate -> 子child updated -> 父dady updated

三、子组件销毁的过程 父 beforeDestroy->子 beforeDestroy->子 destroyed->父 destroyed

**四、 代码演示 父组件 testlife.vue **

<template>
  <div>
    dady
    <MyChild :title="bar" v-if="isshow"></MyChild>
    <a-button @click="destroyHandle"> 销毁子组件</a-button>
  </div>
</template>

<script>
import MyChild from './MyChild'
export default {
  data () {
    return {
      bar: 'uuu',
      isshow: true
    }
  },
  components: {
    MyChild
  },
  beforeCreate () {
    console.log('dady beforeCreate')
  },
  created () {
    console.log('dady Create')
    setTimeout(() => {
      this.bar = '888'
    }, 5000)
  },
  beforeMount () {
    console.log('dady beforeMount')
  },
  methods: {
      destroyHandle () {
        //   this.bar = '99999'
          this.isshow = false
      }
  },
  mounted () {
    console.log('父dady mounted')
  },
  beforeUpdate () {
    console.log('父dady beforeUpdate')
  },
  updated () {
    console.log('父dady updated')
  },
  beforeDestroy () {
      console.log('父dady beforeDestroy')
  },
  destroyed () {
console.log('父dady destroyed')
  }
}
</script>

子组件代码 MyChild.vue

<template>
  <div>child {{ title }}</div>
</template>

<script>
export default {
  props: ['title'],
  beforeCreate () {
    console.log('子child beforeCreate')
  },
  created () {
    console.log('子child Create')
  },
  beforeMount () {
    console.log('子child beforeMount')
  },
  mounted () {
    console.log('子child mounted')
  },
  beforeUpdate () {
    console.log('子child beforeUpdate')
  },
  updated () {
    console.log('子child updated')
  },
   beforeDestroy () {
      console.log('子child beforeDestroy')
  },
  destroyed () {
    console.log('子child destroyed')
  }
}
</script>