zl程序教程

您现在的位置是:首页 >  前端

当前栏目

vue系列:父子组件生命周期的执行顺序

Vue组件执行 系列 顺序 生命周期 父子
2023-09-27 14:27:09 时间

结论

父子组件加载过程

->父beforeCreate -> 父created -> 父beforeMount

->子beforeCreate -> 子created -> 子beforeMount -> 子mounted

-> 父mounted

子组件更新(父组件给子组件传入新的 props 时)

->父beforeUpdate

-> 子beforeUpdate -> 子updated

-> 父updated

父组件销毁

-> 父beforeDestroy

-> 子beforeDestroy -> 子destroyed

-> 父destroyed

测试

<!DOCTYPE html>
<html>

<head>
  <title></title>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
</head>

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

  <script>
    Vue.component('Child', {
      template: '<span>{{ childMsg }}</span>',
      props: {
        childMsg: {
          type: String,
          default: ''
        }
      },
      beforeCreate: function () {
        console.log("子组件的beforeCreate")
      },
      created: function () {
        console.log("子组件的created")
      },
      beforeMount: function () {
        console.log("子组件的beforeMount")
      },
      mounted: function () {
        console.log("子组件的mounted")
      },
      beforeUpdate: function () {
        console.log("子组件的beforeUpdate")
      },
      updated: function () {
        console.log("子组件的updated")
      },
      beforeDestroy: function () {
        console.log("子组件的beforeDestroy")
      },
      destroyed: function () {
        console.log("子组件的destroyed")
      }
    })

    var vm = new Vue({
      el: '#app',
      template: `
      <div>父组件:{{ fatherMsg }}<br>子组件:<Child :childMsg="fatherMsg" /></div>
      `,
      data: {
        fatherMsg: "father"
      },
      beforeCreate: function () {
        console.log("父组件的beforeCreate")
      },
      created: function () {
        console.log("父组件的created")
      },
      beforeMount: function () {
        console.log("父组件的beforeMount")
      },
      mounted: function () {
        console.log("父组件的mounted")
        setTimeout(() => {
          // 触发更新
          // this.fatherMsg = '我变了'
          // 触发销毁
          this.$destroy()
        }, 2000)
      },
      beforeUpdate: function () {
        console.log("父组件的beforeUpdate")
      },
      updated: function () {
        console.log("父组件的updated")
      },
      beforeDestroy: function () {
        console.log("父组件的beforeDestroy")
      },
      destroyed: function () {
        console.log("父组件的destroyed")
      }
    });
  </script>
</body>

</html>