在app.vue写入,注意:v-if 不要写错地方,否则缓存不生效
<router-view v-slot="{ Component }">
<keep-alive>
<component v-if="route.meta && route.meta.keepAlive" :is="Component"/>
</keep-alive>
<component v-if="!(route.meta.keepAlive)" :is="Component"/>
</router-view>
vue-router路由配置
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
const routes: Array<RouteRecordRaw> = [
{
path: "/",
name: "首页",
component: () => import("../home/index.vue"),
meta: {
keepAlive: true // 需要缓存的页面配置
}
},
{
path: "/history",
name: "历史数据",
component: () => import("../history/index.vue"),
}
];
const router = createRouter({
history: createWebHashHistory(),
routes
});
export default router;
我用的是v-if 判断的, 也可以使用 include 和 exclude判断,注意这个是组件名,也就是你.vue文件的定义的name