- 参考:掘金
- 例子:
<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>
<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>
- 结果图: