vue3 keepalive

需求为从列表页进入详情页后返回列表页可以保留页面上的数据、筛选器选择等等

直接在router设置keepalive,实际并不能满足需求,所以使用include + watch 动态改变缓存列表

复制代码
<template>
    <router-view v-slot="{ Component }">
        <keep-alive :include="cachePages">
            <component :is="Component" :key="route.name"/>
        </keep-alive>
    </router-view>
</template>

<script lang="ts" setup>
    const route = useRoute()
    const router = useRouter()
    const cachePages = ref(['List'])
    watch(
        () => router.currentRoute.value.name,
        (to, from) => {
            // 在这里可以执行路由变化时需要做的任何逻辑
            // 从详情页返回时,确保列表页在缓存中
            if (to === 'List' && from === 'Detail') {
                if (!cachePages.value.includes('List')) {
                    cachePages.value.push('List')
                }
            }

            // 从其他页面进入列表页时,移除缓存强制刷新
            else if (to === 'List' && from !== 'Detail') {
                const index = cachePages.value.indexOf('List')
                if (index > -1) {
                    cachePages.value.splice(index, 1)
                }
                // 短暂延迟后重新添加缓存,为了下次返回时能缓存
                setTimeout(() => {
                    if (!cachePages.value.includes('List')) {
                        cachePages.value.push('List')
                    }
                }, 100)
            }
        },
        { deep: true, immediate: true }
    )
</script>

<style scoped>

</style>
相关推荐
ttwuai12 小时前
XYGo Admin 菜单与路由:Vue3 动态路由 + GoFrame 权限菜单的完整实现方案
前端·vue·后台框架
ttwuai16 小时前
XYGo Admin 国际化实战:Vue3 中后台多语言方案详解
前端·javascript·vue.js·vue
还得是你大哥2 天前
Java互联网医院管理系统源码SpringBoot
java·spring boot·vue
会周易的程序员2 天前
aiDgeScanner:工业设备扫描与管理的一体化利器——深度解析上位机与扫描端的无缝协作
c++·物联网·typescript·electron·vue·iot·aiot
阿部多瑞 ABU3 天前
运动会智能编排系统 - 完整详细需求规格说明书
python·贪心算法·vue·html
AIGC包拥它3 天前
RAG 项目实战进阶:基于 FastAPI + Vue3 前后端架构全面重构 LangChain 0.3 集成 Milvus 2.5 构建大模型智能应用
人工智能·python·重构·vue·fastapi·milvus·ai-native
次次皮5 天前
代理启动前端dist包
java·前端·vue
展示猪肝5 天前
Vue2 + FastAPI + Dify 实现 AI 医疗预检分诊助手:从问诊追问到医生审核闭环
人工智能·vue·fastapi·dify
何忆清风6 天前
Easy Agent Pilot - Rust实现的开源桌面Agent软件
ai·rust·vue·agent·tauri·开发工具
码界筑梦坊6 天前
361-基于Python的空气质量气候数据分析预测系统
python·信息可视化·数据分析·flask·vue·毕业设计