fix: 🐛 (keep-alive)重构缓存机制

- 移除 KeepCache 组件,直接在 AppMain 中实现缓存逻辑

- 将 fullPath 做为组件缓存的 name
This commit is contained in:
zimo493
2025-09-01 11:11:45 +08:00
parent e37a6c5aa4
commit cc3750c128
9 changed files with 128 additions and 142 deletions

View File

@@ -1,13 +1,58 @@
<template>
<section class="app-main" :style="{ height: appMainHeight }">
<KeepCache />
<router-view>
<template #default="{ Component, route }">
<transition enter-active-class="animate__animated animate__fadeIn" mode="out-in">
<keep-alive :include="cachedViews">
<component :is="currentComponent(Component, route)" :key="route.fullPath" />
</keep-alive>
</transition>
</template>
</router-view>
</section>
</template>
<script setup lang="ts">
import { useSettingsStore } from "@/store";
import { type RouteLocationNormalized } from "vue-router";
import { useSettingsStore, useTagsViewStore } from "@/store";
import variables from "@/styles/variables.module.scss";
import KeepCache from "@/components/KeepCache/index.vue";
import Error404 from "@/views/error/404.vue";
const { cachedViews } = toRefs(useTagsViewStore());
// 当前组件
const wrapperMap = new Map<string, Component>();
const currentComponent = (component: Component, route: RouteLocationNormalized) => {
if (!component) return;
const { fullPath: componentName } = route; // 使用路由路径作为组件名称
let wrapper = wrapperMap.get(componentName);
if (!wrapper) {
wrapper = {
name: componentName,
render: () => {
try {
return h(component);
} catch (error) {
console.error(`Error rendering component for route: ${componentName}`, error);
return h(Error404);
}
},
};
wrapperMap.set(componentName, wrapper);
}
// 添加组件数量限制
if (wrapperMap.size > 100) {
const firstKey = wrapperMap.keys().next().value;
if (firstKey) {
wrapperMap.delete(firstKey);
}
}
return h(wrapper);
};
const appMainHeight = computed(() => {
if (useSettingsStore().showTagsView) {

View File

@@ -86,14 +86,7 @@ const route = useRoute();
const permissionStore = usePermissionStore();
const tagsViewStore = useTagsViewStore();
const visitedViews = ref<TagView[]>([]);
watchEffect(() => {
visitedViews.value = tagsViewStore.visitedViews;
const names = visitedViews.value.map((item) => item.name).filter(Boolean);
tagsViewStore.setCacheRoutes(names, permissionStore.allCacheRoutes);
});
const { visitedViews } = storeToRefs(tagsViewStore);
// 当前选中的标签
const selectedTag = ref<TagView | null>(null);