Vue——父子组件的生命周期(执行顺序)

一个组件的生命周期:

  • 挂载(初始化相关属性)
    1. beforeCreate
    2. created
    3. beforeMount
    4. mounted
  • 更新(元素或组件的变更操作)
    1. beforeUpdate
    2. updated
  • 销毁(销毁相关属性)
    • beforeDestroy
    • destroyed

结合父子组件之后

一个完整的父子组件生命周期:

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

父组件:

<template>
  <div>
    <input type="text" name="text" id="" v-model="text" />
    <button id="destroy" @click="handle">点击</button>
    <livechidren :text="text"></livechidren>
  </div>
</template>

<script>
import livechidren from "./livechidren.vue";
export default {
  components: { livechidren },
  data() {
    return {
      text: "",
    };
  },
  methods: {
    handle() {
      this.$destroy();
    },
  },
  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>
#destroy{
    width: 80px;
    height: 30px;
    border: none;
    background: rgb(209, 250, 236);
}
</style>

子组件:

<template>
  <div>{{text}}</div>
</template>

<script>
export default {
  data() {
    return {};
  },
  props:{
      text: {
          type: String,
      }
  },
  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>
</style>

结果显示:

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐