Vue 基础篇(四):父子组件的生命周期顺序

本篇将探讨关于Vue中父子组件的生命周期顺序。bash

1、实例代码

父组件:ui

<template>
  <div id="parent">
    <child></child>
  </div>
</template>

<script>
import child from './components/child'
export default {
  name: 'parent',
  components: {
    child
  },
  beforeCreate() {
    console.log('I am parents beforeCreated');
  },
  created() {
    console.log('I am parents created');
  },
  beforeMount() {
    console.log('I am parents beforeMount');
  },
  mounted() {
    console.log('I am parents mounted');
  }
}
</script>
复制代码

子组件:spa

<template>
  <div class="child">
    child
  </div>
</template>

<script>
export default {
  name: 'child',
  beforeCreate() {
    console.log('I am child beforeCreated');
  },
  created() {
    console.log('I am child created');
  },
  beforeMount() {
    console.log('I am child beforeMount');
  },
  mounted() {
    console.log('I am child mounted');
  }
}
</script>
复制代码

执行结果: code

2、结论

咱们从而能够得出父子组件的执行顺序为:component

  • 父组件beforeCreated
  • 父组件created
  • 父组件beforeMounted
  • 子组件beforeCreated
  • 子组件created
  • 子组件beforeMounted
  • 子组件mounted
  • 父组件mounted

注意:cdn

  • 父组件的mounted是在最后执行的。
  • 所以在子组件的mounted中渲染父组件在mounted阶段请求的数据,是会无反应的。由于子组件mounted渲染数据会发生在父组件mounted请求数据以前。
See the Pen Vue父子组件的生命周期顺序 by madman0621 ( @madman0621) on CodePen.
相关文章
相关标签/搜索