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>
相关推荐
在努力的前端小白8 小时前
基于FastAPI+LangChain+LangGraph+Agent+多模态的AI Agent 有渔渔具网站
人工智能·langchain·vue·fastapi
sun_weitao14 小时前
用 FastAPI + MQTT 做一个 ESP32最小化跑通示例
中间件·vue·fastapi
汤米粥5 天前
2026年主流前端技术框架
vue·react·elementplus·tailwind css·angular‌·svelte‌·bootstrap‌
codigger5 天前
Vue nextTick 到底在等什么?一篇讲透原理与那些年踩过的坑
程序员·vue·编程·异步更新·#人工智能
咚咚咚小柒6 天前
【前端】LangChain.js学习
前端·javascript·人工智能·typescript·langchain·vue·ai编程
悟道书生8 天前
若依 RBAC 权限控制学习笔记
java·网络·笔记·sql·学习·vue
mewowaBc8 天前
使用Pinia持久化存储实现用户认证系统
vue·pinia·用户认证系统
gc_22999 天前
使用VS Code终端创建Vue项目报错:“npm : 无法加载文件 ...\npm.ps1,因为在此系统上禁止运行脚本”
vue·vs code
小阿鑫9 天前
尤雨溪 : Vue 4 已经在规划中了!
vue·vite·vite+·程序员海军·vue4
离歌漠9 天前
《我用 Tauri 做了一个本地开发工具箱》
rust·typescript·vue