路由

Nuxt 文件系统路由会为 pages/ 目录中的每个文件创建一个路由。

Nuxt 的核心特性之一是文件系统路由。pages/ 目录中的每个 Vue 文件都会创建一个相应的 URL(或路由),用于显示文件的内容。通过为每个页面使用动态导入,Nuxt 利用代码拆分为请求的路由提供最少量的 JavaScript。

¥One core feature of Nuxt is the file system router. Every Vue file inside the pages/ directory creates a corresponding URL (or route) that displays the contents of the file. By using dynamic imports for each page, Nuxt leverages code-splitting to ship the minimum amount of JavaScript for the requested route.

页面

¥Pages

Nuxt 路由基于 vue-router,并根据文件名为 pages/ 目录 中创建的每个组件生成路由。

¥Nuxt routing is based on vue-router and generates the routes from every component created in the pages/ directory, based on their filename.

此文件系统路由使用命名约定来创建动态和嵌套路由:

¥This file system routing uses naming conventions to create dynamic and nested routes:

-| pages/
---| about.vue
---| index.vue
---| posts/
-----| [id].vue
Read more in Docs > Guide > Directory Structure > Pages.

导航

¥Navigation

<NuxtLink> 组件用于链接各个页面。它会渲染一个 <a> 标签,并将 href 属性设置为页面的路由。应用完成 hydrated 后,页面转换将通过更新浏览器 URL 在 JavaScript 中执行。这可以防止整页刷新并允许动画过渡。

¥The <NuxtLink> component links pages between them. It renders an <a> tag with the href attribute set to the route of the page. Once the application is hydrated, page transitions are performed in JavaScript by updating the browser URL. This prevents full-page refreshes and allows for animated transitions.

<NuxtLink> 进入客户端视口时,Nuxt 会自动预加载链接页面的组件和有效负载(生成的页面),从而加快导航速度。

¥When a <NuxtLink> enters the viewport on the client side, Nuxt will automatically prefetch components and payload (generated pages) of the linked pages ahead of time, resulting in faster navigation.

pages/app.vue
<template>
  <header>
    <nav>
      <ul>
        <li><NuxtLink to="/about">About</NuxtLink></li>
        <li><NuxtLink to="/posts/1">Post 1</NuxtLink></li>
        <li><NuxtLink to="/posts/2">Post 2</NuxtLink></li>
      </ul>
    </nav>
  </header>
</template>
Read more in Docs > API > Components > Nuxt Link.

路由参数

¥Route Parameters

useRoute() 可组合函数可用于 Vue 组件的 <script setup> 块或 setup() 方法中,以访问当前路由详情。

¥The useRoute() composable can be used in a <script setup> block or a setup() method of a Vue component to access the current route details.

pages/posts/[id].vue
<script setup lang="ts">
const route = useRoute()

// When accessing /posts/1, route.params.id will be 1
console.log(route.params.id)
</script>
Read more in Docs > API > Composables > Use Route.

路由中间件

¥Route Middleware

Nuxt 提供了一个可自定义的路由中间件框架,你可以将其用于整个应用,非常适合提取要在导航到特定路由之前运行的代码。

¥Nuxt provides a customizable route middleware framework you can use throughout your application, ideal for extracting code that you want to run before navigating to a particular route.

路由中间件在 Nuxt 应用的 Vue 部分运行。尽管名称相似,但它们与运行在应用 Nitro 服务器部分的服务器中间件完全不同。

路由中间件有三种类型:

¥There are three kinds of route middleware:

  1. 匿名(或内联)路由中间件,直接在使用它们的页面中定义。
  2. 命名路由中间件,放置在 middleware/ 目录中,并在页面上使用时通过异步导入自动加载。(注意:路由中间件名称已规范化为短横线命名,因此 someMiddleware 变为 some-middleware。)
  3. 应用的全局样式将随响应一起发送。

auth 中间件保护 /dashboard 页面的示例:

¥Example of an auth middleware protecting the /dashboard page:

export default defineNuxtRouteMiddleware((to, from) => {
  // isAuthenticated() is an example method verifying if a user is authenticated
  if (isAuthenticated() === false) {
    return navigateTo('/login')
  }
})
Read more in Docs > Guide > Directory Structure > Middleware.

路由验证

¥Route Validation

Nuxt 通过 definePageMeta()validate 属性在每个你希望验证的页面中提供路由验证。

¥Nuxt offers route validation via the validate property in definePageMeta() in each page you wish to validate.

validate 属性接受 route 作为参数。你可以返回一个布尔值来确定这是否是与此页面一起渲染的有效路由。如果你返回 false,并且找不到其他匹配项,则会导致 404 错误。你还可以直接返回一个带有 statusCode/statusMessage 的对象,以立即响应错误(其他匹配项将不会被检查)。

¥The validate property accepts the route as an argument. You can return a boolean value to determine whether or not this is a valid route to be rendered with this page. If you return false, and another match can't be found, this will cause a 404 error. You can also directly return an object with statusCode/statusMessage to respond immediately with an error (other matches will not be checked).

如果你有更复杂的用例,则可以改用匿名路由中间件。

¥If you have a more complex use case, then you can use anonymous route middleware instead.

pages/posts/[id].vue
<script setup lang="ts">
definePageMeta({
  validate: async (route) => {
    // Check if the id is made up of digits
    return typeof route.params.id === 'string' && /^\d+$/.test(route.params.id)
  }
})
</script>
Read more in Docs > API > Utils > Define Page Meta.