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>
相关推荐
IT教程资源D14 小时前
[N_115]基于springboot,vue教务管理系统
mysql·vue·前后端分离·springboot教务系统
嘿siri14 小时前
uniapp enter回车键不触发消息发送,已解决
前端·前端框架·uni-app·vue
@AfeiyuO15 小时前
Vue3 词云
vue·echarts
qq74223498418 小时前
VitePress静态网站从零搭建到GitHub Pages部署一站式指南和DeepWiki:AI 驱动的下一代代码知识平台
人工智能·python·vue·github·vitepress·wiki
是梦终空1 天前
JAVA毕业设计259—基于Java+Springboot+vue3工单管理系统的设计与实现(源代码+数据库+开题报告)
java·spring boot·vue·毕业设计·课程设计·工单管理系统·源代码
@AfeiyuO1 天前
封装表格操作列按钮
vue
千寻技术帮2 天前
10382_基于Springboot的高校排课管理系统
mysql·vue·毕设·spingboot·高校排课
IT教程资源C2 天前
(N_115)基于springboot,vue教务管理系统
mysql·vue·前后端分离·springboot教务系统
沧澜sincerely2 天前
WebSocket 实时聊天功能
网络·websocket·vue·springboot
苏打水com2 天前
第二十篇:Day58-60 前端性能优化进阶——从“能用”到“好用”(对标职场“体验优化”需求)
前端·css·vue·html·js