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

2025-02-27  本文已影响0人  一个小前端程序员
需解决问题
解决问题方案
<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
上一篇 下一篇

猜你喜欢

热点阅读