当我们页面不需要路由缓存,而需要组件缓存时,就可以用下面这种方法处理
<template>
<div style="margin-top: 20px">
<!-- <div>inputVal1: <el-input v-model="inputVal1"></el-input></div> -->
<h3>动态组件展示使用</h3>
<keep-alive :include="include">
<!-- 动态组件 v-bind:is为显示的组件名 -->
<component :is="view"></component>
</keep-alive>
<el-button
v-for="(item, index) in btnList"
:key="index"
@click="select(item.name)"
>切换{{ item.name }}</el-button
>
</div>
</template>
<script>
import acomp from "./HcomA.vue";
import bcomp from "./HcomB.vue";
import ccomp from "./HcomC.vue";
export default {
name: "Home1",
components: {
acomp,
bcomp,
ccomp,
},
data() {
return {
inputVal1: "",
include: ["acomp", "ccomp"],
view: "acomp",
btnList: [
{
id: 1,
name: "a",
},
{
id: 2,
name: "b",
},
{
id: 3,
name: "c",
},
],
};
},
methods: {
select(e) {
this.view = e + "comp";
console.log(this.view);
},
},
beforeRouteEnter(to, from, next) {
console.log(to, from, next);
next();
},
//
beforeRouteLeave(to, from, next) {
console.log(to, from, next);
next();
},
activated() {
console.log("显示A");
},
deactivated() {
console.log("隐藏A");
},
};
</script>
<style lang="scss" scoped></style>
以上代码表示之对acomp和ccomp两个子组件缓存
注意一点就是子组件的name对应这里的23行的名称