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>
相关推荐
医疗信息化王工1 天前
医院自律端系统——预警处置模块全栈实战(ASP.NET Core + Vue3 + Quartz 定时调度)
mysql·postgresql·vue·asp.net core·quartz
大大杰哥1 天前
Vue2学习(1)--了解基本方法与概念
javascript·学习·vue
Agatha方艺璇2 天前
前端开发技术复习笔记
vue·bootstrap·css3·html5·web
小葛要努力2 天前
创建vue2项目
程序人生·vue
七仔啊2 天前
基于海康门禁的人员计数系统
vue
步十人3 天前
【Vue3】前置知识简单概述(包括ES6核心语法,模块化ESM以及npm基础)
arcgis·npm·vue·es6
有梦想的程序星空4 天前
【环境配置】Vue3项目离线化本地部署echarts全攻略
前端·javascript·vue·echarts
向日的葵0064 天前
vue路由(二)
前端·javascript·vue.js·vue
小妖6665 天前
Hydration completed but contains mismatches
javascript·vue·vuepress
lianyinghhh5 天前
FlowGame 从零上手:开源 AI 工作流编排框架与 Vue 3 接入实战
python·低代码·开源·vue·rag·flowgame·ai工作流编排