<keep-alive>、activated 和 deactivated

  1. 参考:掘金
  2. 例子:
  • KeepAlice.vue(父组件)
<template>
  <section>
    <keep-alive>
      <component keyName="name1" :is="componentName"></component>
    </keep-alive>
    <component keyName="name2" :is="componentName"></component>
    <el-button @click="componentName = componentName === 'Son' ? 'Tree' : 'Son'"
      >切换组件,观察生命周期</el-button
    >
  </section>
</template>

<script>
export default {
  data() {
    return {
      componentName: "Son",
    };
  },
  components: {
    Son: () => import("./Son"),
    Tree: () => import("./Tree"),
  },
};
</script>

<style>
</style>

  • Son.vue(子组件)
<template>
  <section>子组件</section>
</template>

<script>
export default {
  props: ["keyName"],
  data() {
    return {};
  },
  created() {
    console.log(this.keyName + " created钩子函数");
  },
  mounted() {
    console.log(this.keyName + " mounted钩子函数");
  },
  activated() {
    console.log(this.keyName + " activated钩子函数");
  },
  deactivated() {
    console.log(this.keyName + " deactivated钩子函数");
  },
};
</script>

<style>
</style>
  1. 结果图:
    image
posted @ 2022-07-12 10:13  拉布拉多~  阅读(79)  评论(0编辑  收藏  举报