Vue3实现tag页面缓存,关闭tag页面不缓存

需解决问题
  • 同时打开多个详情页面,name相同,无法做到tag关闭的不缓存,tag打开的缓存
解决问题方案
  • 给每个组件重命名,参考【formatComponent】函数
<template>
    <div class="view-container-page">
        <router-view v-slot="{ Component }">
            <transition name="slide-right">
                <!-- 直接通过路由配置,来设置是否需要缓存 -->
                <keep-alive :include="cachedPageKeys">
                    <component :key="route.path" :is="formatComponent(Component, route)" />
                </keep-alive>
            </transition>
        </router-view>
    </div>
</template>

<script setup name="viewContainer">
import { useKeepAliveTagsStore } from '@/stores/keepAliveTags';
const keepAliveTagsStore = useKeepAliveTagsStore();
const route = useRoute();

// 需要缓存的页面path
const cachedPageKeys = computed(() => {
    const keepAliveTags = keepAliveTagsStore.getCacheKeepAliveTags;
    return keepAliveTags.map((item) => item.path);
});

// 用来存已经创建的组件
const storeComponents = new Map();
// 原组件包里面
function formatComponent(component, route) {
    let afterComponent;
    if (component) {
        const path = route.path;
        if (storeComponents.has(path)) {
            afterComponent = storeComponents.get(path);
        } else {
            // 关键代码:所有组件重命名,给include参数使用
            afterComponent = {
                name: path,
                render() {
                    return h(component);
                },
            };
            storeComponents.set(path, afterComponent);
        }
        return h(afterComponent);
    }
}
</script>

<style lang="scss" scoped>
.view-container-page {
    width: 100%;
    height: 100%;
    overflow: visible; /* 列表页面展示汇总信息,汇总部分会上移20px超出父元素窗口展示 */
}
</style>

效果截图


微信图片_20250228161600.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容