首页 > 其他 > 详细

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

时间:2019-05-13 16:21:02      阅读:135      评论:0      收藏:0      [点我收藏+]

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,哈哈哈

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

原文:https://www.cnblogs.com/gqx-html/p/10857119.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!