Vue Router嵌套路由如何获取包含父路径的完整绝对路径?
解决Vue Router嵌套路由生成完整绝对路径的问题
我明白你现在的困扰了——在嵌套路由里直接用route.path只能拿到当前子路由的单独路径,没法自动拼接所有父级路径得到完整的绝对URL,对吧?我来帮你搞定这个问题,分几步走:
第一步:先修正你的路由配置(关键前提)
首先要注意Vue Router的嵌套路由规则:子路由的path不要以斜杠/开头,否则它会被当成根路径,而不是相对于父路由的路径。你的现有配置里子路由都用了/开头,这会导致嵌套逻辑失效,所以先把这些斜杠去掉:
{ path:'/meteorologija', name:'meteorologija', component:()=>import('../pages/BlogPage'), children:[ { path:'meteorolosko-bdenje', // 去掉开头的/ name:'meteorolosko bdenje', component:()=>import('../pages/BlogPage'), children:[ { path:'aktuelni-podaci', // 去掉开头的/ name:'aktuelni podaci', component:()=>import('../pages/BlogPage'), children:[ { path:'podaci', name:'Podaci', component:()=>import('../pages/BlogPage') }, { path:'trenutne-temerature', name:'Trenutne temperature', component:()=>import('../pages/BlogPage') }, { path:'ekstremne-temperature', name:'Ekstremne Temperature', component:()=>import('../pages/BlogPage') }, { path:'pritisak', name:'Pritisak', component:()=>import('../pages/BlogPage') }, { path:'vjetar', name:'Vjetar', component:()=>import('../pages/BlogPage') }, { path:'kolicina-padavina', name:'Kolicina padavina', component:()=>import('../pages/BlogPage') }, { path:'radarska-slika', name:'Radarska Slika', component:()=>import('../pages/BlogPage') }, ] } ] } ] }
第二步:编写正确的递归函数生成完整路径
接下来我们写一个递归函数,遍历所有路由,给每个路由添加fullPath属性,这个属性就是包含所有父路径的完整绝对路径:
// 递归生成完整路径的函数 function generateFullPaths(routes, parentPath = '') { routes.forEach(route => { // 拼接当前路由的完整路径:父路径 + 当前路由path // 处理根路由的情况(parentPath为空时直接用当前path) const currentFullPath = parentPath ? `${parentPath}/${route.path}` : route.path; // 给路由添加fullPath属性 route.fullPath = currentFullPath; // 如果当前路由有子路由,递归处理子路由 if (route.children && route.children.length > 0) { generateFullPaths(route.children, currentFullPath); } }); } // 在创建路由实例后调用这个函数 const router = createRouter({ history: createWebHistory(), routes: [/* 你的完整路由数组 */] }); // 给所有路由生成fullPath generateFullPaths(router.options.routes);
第三步:在导航菜单中使用完整路径
现在你就可以在router-link的:to属性里直接用route.fullPath了,比如:
<template> <nav> <ul> <li v-for="route in routes" :key="route.name"> <router-link :to="route.fullPath">{{ route.name }}</router-link> <!-- 如果有子路由,递归渲染子菜单 --> <ul v-if="route.children"> <li v-for="child in route.children" :key="child.name"> <router-link :to="child.fullPath">{{ child.name }}</router-link> </li> </ul> </li> </ul> </nav> </template>
为什么你的原函数没生效?
你之前写的递归函数有两个关键问题:
- 传递的
path参数是对象path={},但我们需要的是字符串类型的父路径,对象无法正确拼接路径; - 没有把拼接后的路径赋值给路由的属性,也没有正确处理父路径和当前路径的拼接逻辑。
现在按照上面的步骤来,就能完美解决嵌套路由的完整路径问题啦~
内容的提问来源于stack exchange,提问作者curious lad
相关产品推荐
相关产品推荐

