How to use keep-alive to cache nested route pages #2406
-
I have route like this: routes: [
{
path: '/',
redirect: '/setting/1/user/1',
},
{
path: '/setting/:sid',
component: () => import('@/views/settings.vue'),
children: [
{
path: 'user/:uid',
component: () => import('@/views/user.vue'),
},
],
},
], I try to use the router-view slot and keep-alive to cache the route components as written in the documentation: <router-view v-slot="{ Component }">
<component :is="Component" />
</router-view> But all <router-view v-slot="{ Component, route }">
<keep-alive>
<component :is="Component" :key="route.path" />
</keep-alive>
</router-view> Another problem occurs that In a nutshell, can I get something like the “current path” in a nested route: for the path |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Found one solution, here is code, maybe more boundary conditions need to be considered: <template lang="pug">
router-view(#='{ Component, route }')
template(v-if='Component')
transition(mode='out-in')
keep-alive
component(:is='Component', :key='getKey(route, Component)')
</template>
<script setup lang="ts">
import { pathToRegexp } from 'path-to-regexp'
import { type RouteLocationNormalizedLoaded } from 'vue-router'
function getKey(route: RouteLocationNormalizedLoaded, Component: VNode) {
const matched = route.matched.find(
m => m.components?.default === Component.type
)
if (!matched) return route.path
const { regexp } = pathToRegexp(matched.path, { end: false }),
currentPath = route.path.match(regexp)?.[0] ?? route.path
return currentPath
}
</script> |
Beta Was this translation helpful? Give feedback.
Found one solution, here is code, maybe more boundary conditions need to be considered: