Files
lanecarford_front/src/components/RouteCache.vue

60 lines
1.5 KiB
Vue
Raw Normal View History

2025-10-21 11:21:15 +08:00
<template>
<router-view v-slot="{ Component, route }">
<keep-alive :include="cachedViews">
<component :is="Component" :key="route.name" />
</keep-alive>
</router-view>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
// 缓存的组件名称列表
const cachedViews = ref<string[]>([])
// 监听路由变化,管理缓存
watch(
() => route,
(newRoute) => {
const routeName = newRoute.name as string
const shouldCache = newRoute.meta?.cache === true
2025-10-21 11:28:12 +08:00
// console.log('🔄 路由变化:', { routeName, shouldCache, currentCache: cachedViews.value })
2025-10-21 11:21:15 +08:00
if (shouldCache && routeName && !cachedViews.value.includes(routeName)) {
cachedViews.value.push(routeName)
2025-10-21 11:28:12 +08:00
// console.log('✅ 添加到缓存:', routeName)
2025-10-21 11:21:15 +08:00
} else if (!shouldCache && routeName && cachedViews.value.includes(routeName)) {
// 从缓存列表中移除
const index = cachedViews.value.indexOf(routeName)
if (index > -1) {
cachedViews.value.splice(index, 1)
2025-10-21 11:28:12 +08:00
// console.log('❌ 从缓存移除:', routeName)
2025-10-21 11:21:15 +08:00
}
}
},
{ immediate: true, deep: true }
)
// 提供清除缓存的方法
const clearCache = (routeName?: string) => {
if (routeName) {
const index = cachedViews.value.indexOf(routeName)
if (index > -1) {
cachedViews.value.splice(index, 1)
}
} else {
cachedViews.value = []
}
}
// 暴露方法供外部使用
defineExpose({
clearCache,
cachedViews
})
</script>