vue父子組件生命周期執行順序


之前寫了vue的生命周期,本以為明白了vue實例在創建到顯示在頁面上以及銷毀等一系列過程,以及各個生命周期的特點。然而今天被問到父子組件生命周期執行順序的時候一頭霧水,根本不知道怎么回事。然后寫了一段demo驗證一下大佬們說的順序。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/vue-2.4.0.js"></script>
</head>

<body>
  <div id="app">
    <login></login>
  </div>

  <script>
    var login = {
      template: '<h1>{{childMsg}}}</h1>',
      data(){
        return {
          childMsg:'child'
        }
      },  
      beforeCreate: function () {
        debugger;
        console.log("子組件的beforeCreate")
      },
      created: function () {
        debugger
        console.log("子組件的created")
      },
      beforeMount: function () {
        debugger
        console.log("子組件的beforeMount")
      },
      mounted: function () {
        debugger
        console.log("子組件的mounted")
      }
    }

    var vm = new Vue({
      el: '#app',
      data: {
        fatherMsg: "father"
      },
      methods: {},
      components: {
        login
      },
      beforeCreate: function () {
        debugger
        console.log("父組件的beforeCreate")
      },
      created: function () {
        debugger
        console.log("父組件的created")
      },
      beforeMount: function () {
        debugger
        console.log("父組件的beforeMount")
      },
      mounted: function () {
        debugger
        console.log("父組件的mounted")
      },
    });
  </script>
</body>

</html>

運行此代碼,打開f12,進入sources里邊

1.首先執行的是父組件的beforeCreate

2.執行的是父組件的created周期

 

3.執行的是父組件的beforeMount周期

 

4.執行的是子組件的beforeCreate周期

 

5.執行的是子組件的created周期

 

6.執行的是子組件的beforeMount周期

 

7.執行的是子組件的mounted周期

 

8.執行的是父組件的mounted周期

 

總結:

通過上邊一步步的debugger,我們可以發現父子組件在加載的時候,執行的先后順序為父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount->子mounted->父mounted。

然后我們通過控制台打印的結果進一步證實了這個順序。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM