Nuxt.js是否支持无限动态层级嵌套路由?
Absolutely! Nuxt.js fully supports infinitely nested dynamic routes—exactly what you need for handling those arbitrary depth pages your users might create. Let’s break down how to implement this in both Nuxt 2 and Nuxt 3, since the approach differs a bit between versions.
In Nuxt 2, you can use a catch-all route by creating a file named _.vue in your pages directory. This file will match any URL that isn’t handled by other existing routes, regardless of how many nested levels it has.
Here’s a simple example component:
<!-- pages/_.vue --> <template> <div> <h1>Dynamic Nested Page</h1> <p>Full path: {{ $route.params.pathMatch }}</p> <p>Individual segments: {{ pathSegments }}</p> </div> </template> <script> export default { computed: { pathSegments() { // Split the full path into segments, filtering out empty strings return this.$route.params.pathMatch.split('/').filter(segment => segment) } } } </script>
When a user visits /parent/level-1/level-2/level-3, $route.params.pathMatch will be the string parent/level-1/level-2/level-3, and pathSegments will be an array ['parent', 'level-1', 'level-2', 'level-3']—you can use these segments to fetch the corresponding content for the page.
Nuxt 3 uses Vue Router 4 under the hood, which offers more flexible wildcard routing options. There are two common approaches here:
1. Catch-All Page in pages Directory
Create a file named [...slug].vue in your pages directory. The ... syntax tells Vue Router to capture all remaining path segments as an array.
Example component:
<!-- pages/[...slug].vue --> <template> <div> <h1>Dynamic Nested Page (Nuxt 3)</h1> <p>Path segments: {{ slug }}</p> </div> </template> <script setup> const route = useRoute() // `slug` will be an array of path segments (e.g., ['parent', 'level-1', 'level-2'] for /parent/level-1/level-2) const slug = route.params.slug || [] </script>
2. Custom Route Configuration
If you only want to match nested paths under a specific prefix (like /parent/), you can extend the router config in nuxt.config.ts:
// nuxt.config.ts export default defineNuxtConfig({ router: { extendRoutes(routes, resolve) { routes.push({ name: 'parent-nested', path: '/parent/*', component: resolve(__dirname, 'pages/parent-nested.vue'), }) }, }, })
Then create the corresponding component to handle the nested path:
<!-- pages/parent-nested.vue --> <template> <div> <h1>Parent Nested Page</h1> <p>Full nested path: {{ route.params.pathMatch }}</p> <p>Segments: {{ pathSegments }}</p> </div> </template> <script setup> const route = useRoute() const pathSegments = route.params.pathMatch.split('/').filter(s => s) </script>
In both versions, you can use the captured path segments to dynamically load content (like fetching data from an API based on the segments) to render the correct page for your users.
内容的提问来源于stack exchange,提问作者kindisch

