父子组件生命周期的执行顺序

创建阶段:

  父组件的beforeCreated => 父组件的Created => 父组件的beforeMount => 子组件的beforeCreated => 子组件的Created => 子组件的beforeMount => 子组件的mounted => 父组件的mounted

更新阶段:

  父组件的beforeUpdate =>子组件的beforeUpdate => 子组件的updated => 父组件的updated

销毁阶段:父组件销毁

  父组件的beforeDestroy => 子组件的beforeDestroy =>子组件的destroyed => 父组件的destroyed

销毁阶段:子组件销毁

子组件的beforeDestroy
子组件的destroyed

代码示例

<div id="app">
    <button @click="destroy">销毁</button>
    <p>{{fatherMsg}}</p>
    <child :message="fatherMsg" @fn="getChildMsg"></child>
  </div>

  <template id="child">
    <div>
      <button @click="destroy">子组件销毁</button>
      {{msg}}---{{message}}
    </div>
  </template>

  <script>
    //创建Vue实例,得到 ViewModel
    var vm = new Vue({
      el: '#app',
      data: {
        fatherMsg: 20
      },
      methods: {
        getChildMsg(value) {
          this.fatherMsg = value;
        },
        destroy() {
          this.$destroy();
        }
      },
      beforeCreate() {
        console.log("父组件的beforeCreated");
      },
      created() {
        console.log("父组件的Created");
      },
      beforeMount() {
        console.log("父组件的beforeMount");
      },
      mounted() {
        console.log("父组件的mounted");
      },
      beforeUpdate() {
        console.log("父组件的beforeUpdate");
      },
      updated() {
        console.log("父组件的updated");
      },
      beforeDestroy() {
        console.log("父组件的beforeDestroy");
      },
      destroyed() {
        console.log("父组件的destroyed");
      },
      components: {
        child: {
          template: '#child',
          data() {
            return {
              msg: 10,
            };
          },
          props: {
            "message": {
              type: Number
            }
          },
          watch: {
            msg(newValue) {
              this.$emit('fn', newValue);
            },
          },
          methods: {
            destroy() {
              this.$destroy();
            }
          },
          beforeCreate() {
            console.log("子组件的beforeCreated");
          },
          created() {
            console.log("子组件的Created");
          },
          beforeMount() {
            console.log("子组件的beforeMount");
          },
          mounted() {
            console.log("子组件的mounted");
          },
          beforeUpdate() {
            console.log("子组件的beforeUpdate");
          },
          updated() {
            console.log("子组件的updated");
          },
          beforeDestroy() {
            console.log("子组件的beforeDestroy");
          },
          destroyed() {
            console.log("子组件的destroyed");
          }
        }
      },
    });
  </script>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值