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.
相關文章
相關標籤/搜索