只是实现了一种最简单的例子,当子页面跳转回父页面,且父页面设置了keppAlive时,保留缓存
vue文件
<template>
<div>
<router-view v-slot="{ Component }">
<keep-alive :include="keepAlive">
<component :is="Component" />
</keep-alive>
</router-view>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive } from 'vue';
export default defineComponent({
setup(): any {
return reactive({
keepAlive: [],
});
},
watch: {
$route(to, from) {
const isKeep = to.meta.keepAlive;
let isInclude = false;
const toPathList = to.path.split('/');
const fromPathList = from.path.split('/');
if (fromPathList[1] === toPathList[1]) {
isInclude = true;
}
//keep-alive处理
if (isKeep && !isInclude) {
this.keepAlive = [to.name];
}
if (!isKeep && !isInclude) {
this.keepAlive = [];
}
},
},
});
</script>
router文件
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
export const constantRoutes: Array<RouteRecordRaw> = [
{
path: '/clientView',
component: () => import('@/views/a/index.vue'),
name: 'clientView',
meta: {
title: "Overview",
keepAlive: true,//设置keepAlive即表示父子页面跳转时,该页面需要缓存
},
},
{
path: '/clientView/detail',
component: () => import('@/views/a/Detail.vue'),
name: 'clientViewDetail',
meta: {
title: "Detail",
},
},
]
/** 动态路由 */
export const asyncRoutes: Array<RouteRecordRaw> = [];
const router = createRouter({
history: createWebHashHistory(),
routes: constantRoutes,
});
export default router;