在 Vue3 + TypeScript 项目中管理路由缓存可以通过以下步骤实现,确保灵活性和可维护性:
确保需要缓存的组件显式声明 name
属性。使用 defineOptions
或 unplugin-vue-define-options
插件(适用于 <script setup>
):
<script setup lang="ts">
// 组件的逻辑
</script>
<script lang="ts">
export default defineComponent({
name: 'ListPage' // 必须唯一
})
</script>
在路由的 meta
字段中标记是否需要缓存:
// router.ts
const routes = [
{
path: '/list',
component: () => import('@/views/ListPage.vue'),
meta: {
keepAlive: true // 需要缓存
}
},
{
path: '/detail/:id',
component: () => import('@/views/DetailPage.vue'),
meta: {
keepAlive: false // 不需要缓存
}
}
]
创建 Store 管理缓存组件名:
// stores/routeCache.ts
import { defineStore } from 'pinia'
export const useRouteCache = defineStore('routeCache', {
state: () => ({
cacheComponents: new Set<string>() // 使用 Set 避免重复
}),
actions: {
add(name: string) {
this.cacheComponents.add(name)
},
remove(name: string) {
this.cacheComponents.delete(name)
},
clear() {
this.cacheComponents.clear()
}
}
})
在全局路由守卫中动态管理缓存:
// router.ts
router.beforeEach((to, from) => {
const cacheStore = useRouteCache()
// 缓存来源页面(根据业务逻辑调整)
if (from.meta.keepAlive) {
const componentName = from.matched[0]?.components?.default?.name
if (componentName) cacheStore.add(componentName)
}
// 清除目标页面缓存(如需要)
if (!to.meta.keepAlive) {
const componentName = to.matched[0]?.components?.default?.name
if (componentName) cacheStore.remove(componentName)
}
})
在根组件中绑定缓存的组件名:
<!-- App.vue -->
<template>
<router-view v-slot="{ Component, route }">
<keep-alive :include="Array.from(cacheStore.cacheComponents)">
<component :is="Component" :key="route.fullPath" />
</keep-alive>
</router-view>
</template>
<script setup lang="ts">
import { useRouteCache } from '@/stores/routeCache'
const cacheStore = useRouteCache()
</script>
使用 onActivated
和 onDeactivated
处理数据刷新:
<script setup lang="ts">
import { onActivated } from 'vue'
// 重新获取数据(如果需要)
onActivated(() => {
fetchData()
})
</script>
key
或 meta
附加标识区分。<keep-alive :max="5">
限制最大缓存实例,避免内存问题。通过以上方案,可实现灵活的路由缓存管理,适应大多数业务场景,同时保持代码清晰和可维护性。