如何在Nuxt中创建支持多层分类的递归动态路由
在Nuxt中实现动态可变层级的分类路由
要实现你这种层级不固定的分类路由,核心是用Nuxt的通配符动态路由(Catch-all Routes),它能匹配任意深度的路径片段,完美适配多级子分类的场景。
1. 创建路由文件结构
在pages目录下按如下结构创建文件:
pages/ └── blog/ └── [...categoryPath]/ └── [article-handle].vue
这个文件会匹配所有形如blog/分类1/分类2/.../分类N/文章handle的URL,不管分类层级有多深。
2. 获取路由参数
在组件里,通过Vue Router的useRoute钩子就能拿到分类路径和文章handle:
import { useRoute } from 'vue-router' const route = useRoute() // categoryPath是一个数组,对应URL里的分类片段 // 比如URL是blog/animals-pets/animal-health/animal-hospital/my-post,数组就是['animals-pets', 'animal-health', 'animal-hospital'] const categoryPath = route.params.categoryPath || [] const articleHandle = route.params.articleHandle
3. 页面逻辑实现
因为所有分类层级的页面逻辑一致,你只需要基于categoryPath数组来动态调整内容和面包屑:
面包屑生成
遍历categoryPath数组,拼接每个分类的跳转链接和显示名称(注意要把handle转成友好的分类名,可通过后端接口或本地映射表实现):
<nav class="breadcrumb"> <router-link to="/blog">Blog</router-link> <span v-for="(handle, idx) in categoryPath" :key="handle"> / <router-link :to="`/blog/${categoryPath.slice(0, idx+1).join('/')}`"> {{ getCategoryName(handle) }} </router-link> </span> / {{ articleTitle }} </nav>
内容获取
把categoryPath传给后端接口,获取对应分类下的文章详情:
// 示例接口调用,实际根据你的后端逻辑调整 const fetchArticle = async (handle, categorySegments) => { const categoryPathStr = categorySegments.join('/') const res = await fetch(`/api/articles/${categoryPathStr}/${handle}`) return res.json() } const { articleTitle, articleContent } = await fetchArticle(articleHandle, categoryPath)
额外补充:分类列表页面
如果需要单独的分类列表页(比如blog/animals-pets/animal-health,不带文章handle),可以再创建pages/blog/[...categoryPath].vue,逻辑和文章页类似,只是接口换成获取分类下的文章列表即可。
路由优先级说明
Nuxt会优先匹配更具体的路由,所以如果你的项目里有固定层级的路由文件,它会比通配符路由先触发。但在你的场景下,直接用通配符路由就能覆盖所有层级的需求,不需要额外配置。
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

