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

我们都知道Vue2中八大 生命周期钩子

第一部分-初始化相关属性

beforeCreate created beforeMount mounted

第二部分-更新数据

beforeUpdate updated

第三部分-销毁相关属性

beforeDestroy  destroyed

当我们结合父子组件使用时

父组件中

<template>
  <div class="father" v-if="IsDisplay">
    <h2>父组件- {{num}} </h2>
    <button @click="num++">更新</button>
    <button @click="IsDisplay = false">隐藏</button>
    <static2Child :num ='num' ></static2Child>
  </div>
</template>

<script>
import static2Child from '@/views/staticRoutes/static2Child'
export default {
  name: "Vue2TestStatic2",
  // 注册组件
  components:{
      static2Child,
  },
  data() {
      return {
          num: 0,
          IsDisplay: true,
      };
  },

  beforeCreate() {
    console.log("父beforeCreate");
  },
  created() {
    console.log("父create");
  },
  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>

<style lang="scss" scoped>
.father{
    width: 500px;
    height: 300px;
    border: 1px solid black;

}
</style>

子组件中

<template>
  <div class="son">
    我是子组件-{{ num }}

  </div>
</template>

<script>
export default {
  name: "Vue2TestStatic2Child",
  props: {
    num: {
      type: Number,
      default: 0,
    },
  },

  beforeCreate() {
    console.log("子beforeCreate");
  },
  created() {
    console.log("子create");
  },
  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>

<style lang="scss" scoped>
.son {
  width: 200px;
  height: 50px;
  border: 1px solid pink;
}
</style>

挂载阶段

更新阶段

销毁阶段 (存在问题 没有让父组件‘自己销毁’ 显示父组件在更新)

结论

父beforeCreate -> 父created -> 父beforeMount -> 子beforeCreate -> 子created -> 子beforeMount -> 子mounted -> 父mounted->父beforeUpdate->子beforeUpdate->子updated->父updated->父beforeDestroy->子beforeDestroy->子destroyed->父destroyed

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值