Merge branch 'master' of https://gitee.com/lvYeJu/lane-crawford-3
This commit is contained in:
59
src/components/RouteCache.vue
Normal file
59
src/components/RouteCache.vue
Normal file
@@ -0,0 +1,59 @@
|
||||
<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
|
||||
|
||||
// console.log('🔄 路由变化:', { routeName, shouldCache, currentCache: cachedViews.value })
|
||||
|
||||
if (shouldCache && routeName && !cachedViews.value.includes(routeName)) {
|
||||
cachedViews.value.push(routeName)
|
||||
// console.log('✅ 添加到缓存:', routeName)
|
||||
} else if (!shouldCache && routeName && cachedViews.value.includes(routeName)) {
|
||||
// 从缓存列表中移除
|
||||
const index = cachedViews.value.indexOf(routeName)
|
||||
if (index > -1) {
|
||||
cachedViews.value.splice(index, 1)
|
||||
// console.log('❌ 从缓存移除:', routeName)
|
||||
}
|
||||
}
|
||||
},
|
||||
{ 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>
|
||||
Reference in New Issue
Block a user