vue中父级与子组件生命周期的先后顺序

1.vue的生命周期

image.png

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.打印看一下什么情况

image.png

从打印我们可以看出来,父级beforeMount挂载开始时才会进入到子级beforeCreate实例化开始,但是子级mounted挂载实例比父级mounted挂载实例要快1毫秒,为什么呢?并且子级初次渲染时没有数据更新,那什么时候子级会数据更新呢?

5.子级mounted挂载实例比父级mounted挂载实例要快1毫秒

当父组件执行完beforeMount挂载开始后,会依次执行子组件中的钩子,直到全部子组件mounted挂载到实例上,父组件才会进入mounted钩子

6.子级数据更新

当对子级进行事件处理时,就会触发哦,从下图可以看出,子级进行事件,会先触发父级beforeUpdate钩子,再去触发子级beforeUpdate钩子,下面又是先执行子级updated钩子,后执行父级updated钩子,同理与5相同

image
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容