Nuxt 的路由核心就是文件路由。
<!-- app/pages/index.vue -->
<template>
<h1>首页</h1>
</template>对应:
/<!-- app/pages/about.vue -->
<template>
<section>关于电视台</section>
</template>对应:
/about#1. 动态路由 —— 可变栏目编号
<!-- app/pages/news/[slug].vue -->
<script setup lang="ts">
const route = useRoute()
</script>
<template>
<article>新闻稿:{{ route.params.slug }}</article>
</template>对应:
/news/ai-breakthrough
/news/new-framework#2. 可选参数 —— 有这个栏目也行,没有也行
Nuxt 文档里说明,双中括号表示可选参数。
app/pages/[[slug]].vue这类页面既能匹配 /,也能匹配 /test。
#3. 捕获所有路径 —— 总机转接台
app/pages/[...slug].vue这种路由适合:
- CMS 内容页
- 文档系统
- 多级栏目页
#4. 嵌套路由 —— 一个节目里套子栏目
pages/
├── parent.vue
└── parent/
└── child.vue父页面里需要显式放 <NuxtPage />,子页面才能显示。
<!-- app/pages/parent.vue -->
<template>
<div>
<h1>父栏目</h1>
<NuxtPage />
</div>
</template>#5. 路由组 —— 编排分组,不影响播出地址
Nuxt 4 文档里还有很实用的 route groups:
pages/
├── index.vue
└── (marketing)/
├── about.vue
└── contact.vue最终 URL 还是:
/
/about
/contact括号目录只是为了组织代码,不会进入 URL。
这很像电视台内部把节目分到“新闻部”“市场部”,但观众看到的频道号不变。