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

vue的生命周期想必都不陌生,但是加上子组件,那这个生命周期执行顺序就变成了:

父组件beforeCreate > 父组件created > 父组件beforeMount > 子组件beforeCreate > 子组件created > 子组件beforeMount > 子组件mounted > 父组件mounted > 父组件beforeDestroy > 子组件beforeDestroy > 子组件destroyed > 父组件destroyed

总结一下就是:

父组件在执行到beforeMount之后,子组件会执行到mounted,然后父组件再执行mounted。

销毁的时候,父组件先执行beforeDestroy,然后子组件执行beforeDestroy和destroyed 后,父组件才执行destroyed。

当父组件给子组件传参,进行更新的时候

父组件beforeUpdate > 子组件beforeUpdate > 子组件updated > 父组件updated

以下为代码验证:

父组件:

<template>
  <div>
    <p>父组件{{currentTime}}</p>
    <childCompontent :currentTime="currentTime" />
  </div>
</template>

<script>
import childCompontent from "../components/HelloWorld";
export default {
  data() {
    return {
      currentTime: ""
    };
  },
  components: { childCompontent },
  beforeCreate() {
    console.log("父组件beforeCreate");
  },
  created() {
    console.log("父组件created");
  },
  beforeMount() {
    console.log("父组件beforeMount");
  },
  mounted() {
    this.timer = setInterval(() => {
      this.currentTime = new Date().getSeconds();
    }, 1000);
    console.log("父组件mounted");
  },
  beforeUpdate() {
    console.log("父组件beforeUpdate");
  },
  updated() {
    console.log("父组件updated");
  },
  beforeDestroy() {
    clearInterval(this.timer);
    debugger;
    console.log("父组件beforeDestroy");
  },
  destroyed() {
    debugger;
    console.log("父组件destroyed");
  }
};
</script>

子组件:

<template>
  <div>
    <p>子组件{{currentTime}}</p>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: ["currentTime"],
  beforeCreate() {
    console.log("子组件beforeCreate");
  },
  created() {
    console.log("子组件created");
  },
  beforeMount() {
    console.log("子组件beforeMount");
  },
  mounted() {
    console.log("子组件mounted");
  },
  beforeUpdate() {
    console.log("子组件beforeUpdate");
  },
  updated() {
    console.log("子组件updated");
  },
  beforeDestroy() {
    debugger;
    console.log("子组件beforeDestroy");
  },
  destroyed() {
    debugger;
    console.log("子组件destroyed");
  }
};
</script>
  • 1
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值