activated()deactivated()

activated()和deactivated()只有在包裹的时候才有效。

新建两个组件,comA,comB

<template>
  <div>COMA</div>
</template>

<script>
export default {
  name: "ComA",
  activated() {
    console.log("A>>>activated");
  },
  deactivated() {
    console.log("A>>>deactivated");
  },
};
</script>

<style></style>
<template>
  <div>COMB</div>
</template>

<script>
export default {
  name: "ComB",
};
</script>

<style></style>

然后引用两个组件
html部分:

    <button @click="showCom = 'ComA'">切换到A</button>
    <button @click="showCom = 'ComB'">切换到B</button>
    <component :is="showCom"> </component>
import ComA from "@/components/comA.vue";
import ComB from "@/components/comB.vue";
//......
components: { Test, ComA, ComB },
  data() {
    return {
      graph: null,
      showCom: "ComA",
    };
  },

此时当我们点击按钮切换展示的组件时,发现ComA中的activated()deactivated(),并没有打印出来。然后我们使用<keep-alive></keep-alive>包裹。刷新页面后,查看控制台alt 发现ComAactivated被执行了,点击按钮切换到ComB,发现ComAdeactivated执行了alt

总结:
activated被 keep-alive 缓存的组件激活时调用。
deactivated被 keep-alive 缓存的组件失活时调用。