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>
包裹。刷新页面后,查看控制台
发现
ComA
的activated
被执行了,点击按钮切换到ComB
,发现ComA
的deactivated
执行了
总结:
activated
被 keep-alive 缓存的组件激活时调用。
deactivated
被 keep-alive 缓存的组件失活时调用。