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>
相关推荐
南_山无梅落6 天前
从传统Web到API驱动:使用Django REST Framework重构智能合同审查系统
重构·django·vue·drf
PD我是你的真爱粉7 天前
API 请求封装(Axios + 拦截器 + 错误处理)
前端框架·vue
biyezuopinvip8 天前
基于Spring Boot的投资理财系统设计与实现(毕业论文)
java·spring boot·vue·毕业设计·论文·毕业论文·投资理财系统设计与实现
biyezuopinvip8 天前
基于Spring Boot的投资理财系统设计与实现(任务书)
java·spring boot·vue·毕业设计·论文·任务书·投资理财系统设计与实现
huohuopro9 天前
Vue3 Webview 转 Android 虚拟导航栏遮挡问题记录
android·vue
码界筑梦坊10 天前
332-基于XGBoost与SHAP的可穿戴设备亚健康风险识别系统
python·数据分析·flask·vue·毕业设计
上单带刀不带妹10 天前
【Axios 实战】网络图片地址转 File 对象,附跨域解决方案
开发语言·前端·javascript·vue
SuperEugene10 天前
前端模块化与 import/export入门:从「乱成一团」到「清晰可维护」
前端·javascript·面试·vue
~央千澈~11 天前
优雅草正版授权系统 - 优雅草科技开源2月20日正式发布
python·vue·php·授权验证系统
Roc.Chang11 天前
Vite 启动报错:listen EACCES: permission denied 0.0.0.0:80 解决方案
linux·前端·vue·vite