Skip to Content
Nuxt
指南实用配方

自定义路由

在 Nuxt 中,你的路由由 pages 目录内文件的结构定义。不过,由于底层使用了 vue-router,Nuxt 提供了几种在你的项目中添加自定义路由的方式。

添加自定义路由

在 Nuxt 中,你的路由由 app/pages 目录 内文件的结构定义。不过,由于底层使用了 vue-router,Nuxt 提供了几种在你的项目中添加自定义路由的方式。

路由配置(Router Config)

使用路由选项,你可以选择使用一个函数覆盖或扩展你的路由,该函数接收扫描到的路由并返回定制后的路由。

如果它返回 null 或 undefined,Nuxt 会回退到默认路由(这对于修改输入的数组很有用)。

import type { RouterConfig } from '@nuxt/schema'

export default {
  // https://router.vuejs.org/api/interfaces/routeroptions#routes
  routes: _routes => [
    {
      name: 'home',
      path: '/',
      component: () => import('~/pages/home.vue'),
    },
  ],
} satisfies RouterConfig

Nuxt 不会为你从 routes 函数返回的、提供组件中的 definePageMeta 定义的任何新路由补充元数据。如果你希望如此,应该使用 pages:extend 钩子,它在构建时调用。

Pages 钩子

你可以使用 pages:extend nuxt 钩子,从扫描到的路由中添加、修改或移除页面。

例如,阻止为任何 .ts 文件创建路由:

import type { NuxtPage } from '@nuxt/schema'

export default defineNuxtConfig({
  hooks: {
    'pages:extend' (pages) {
      // 添加一个路由
      pages.push({
        name: 'profile',
        path: '/profile',
        file: '~/extra-pages/profile.vue',
      })

      // 移除路由
      function removePagesMatching (pattern: RegExp, pages: NuxtPage[] = []) {
        const pagesToRemove: NuxtPage[] = []
        for (const page of pages) {
          if (page.file && pattern.test(page.file)) {
            pagesToRemove.push(page)
          } else {
            removePagesMatching(pattern, page.children)
          }
        }
        for (const page of pagesToRemove) {
          pages.splice(pages.indexOf(page), 1)
        }
      }
      removePagesMatching(/\.ts$/, pages)
    },
  },
})

Nuxt 模块

如果你计划添加一整套与某个特定功能相关的页面,你可能会想使用一个 Nuxt 模块。

Nuxt kit 提供了几种添加路由 的方式:

  • extendPages(回调:pages => void)
  • extendRouteRules(route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions)

路由选项

除了为 vue-router 自定义选项外,Nuxt 还提供了额外选项 来定制路由器。

使用 router.options

这是推荐的方式来指定路由选项。

import type { RouterConfig } from '@nuxt/schema'

export default {
} satisfies RouterConfig

可以通过在 pages:routerOptions 钩子中添加文件,来添加更多路由选项文件。数组中的靠后项会覆盖靠前的项。

在此钩子中添加路由选项文件会开启基于页面的路由,除非设置了 optional,在这种情况下,它只会在基于页面的路由已启用时生效。

import { createResolver } from '@nuxt/kit'

export default defineNuxtConfig({
  hooks: {
    'pages:routerOptions' ({ files }) {
      const resolver = createResolver(import.meta.url)
      // 添加一个路由
      files.push({
        path: resolver.resolve('./runtime/router-options'),
        optional: true,
      })
    },
  },
})

使用 nuxt.config

注意: 只有可 JSON 序列化的选项 可被配置:

  • linkActiveClass
  • linkExactActiveClass
  • end
  • sensitive
  • strict
  • hashMode
  • scrollBehaviorType
export default defineNuxtConfig({
  router: {
    options: {},
  },
})

路由默认是大小写敏感的,以匹配 Nitro。将 router.options.sensitive 设为 false 可以退出这一行为。sensitive 只能在 nuxt.config 中设置:如果 router.options 文件设置了它,构建会失败。

大小写不敏感路由下的路由规则

在 sensitive: false 下,Nuxt 会先把请求路径和规则模式都转为小写,再匹配路由规则。模式中的正则约束会按原样保留,因此它们必须针对小写字母书写:/products/:id([a-z0-9]+) 可以匹配 /Products/ABC1。

如果某个约束能匹配大写字母却无法匹配其小写形式,例如 [A-Z]、\x41 或 (?:FOO),或者它是一个只排除了其中一种形式的取反字符类,例如 [^a-z],构建就会失败。请改用 [a-z]。

大小写不敏感路由下的服务端中间件

Nitro 对服务端中间件的 route 是按大小写敏感匹配的。在 sensitive: false 下,通过 serverHandlers 或 addServerHandler 为 /admin/** 注册的中间件不会在 /Admin 上运行,但页面路由器仍然会在 /admin 渲染该页面。如果你使用服务端中间件来保护页面,请保持 sensitive 为 true。

Hash 模式(SPA)

你可以使用 hashMode 配置 在 SPA 模式下启用 hash history。在此模式下,路由器会在内部传递的实际 URL 之前使用一个井号字符(#)。启用后,URL 永远不会发送到服务器,且不支持 SSR。

export default defineNuxtConfig({
  ssr: false,
  router: {
    options: {
      hashMode: true,
    },
  },
})

Hash 链接的滚动行为

你可以选择自定义 hash 链接的滚动行为。当你将该配置 设为 smooth,并加载一个带有 hash 链接的页面时(例如 https://example.com/blog/my-article#comments),你会看到浏览器平滑滚动到这个锚点。

export default defineNuxtConfig({
  router: {
    options: {
      scrollBehaviorType: 'smooth',
    },
  },
})

自定义历史模式(进阶)

你可以选择一个使用函数覆盖历史模式,该函数接收 base URL 并返回历史模式。如果它返回 null 或 undefined,Nuxt 会回退到默认的历史模式。

import type { RouterConfig } from '@nuxt/schema'
import { createMemoryHistory } from 'vue-router'

export default {
  // https://router.vuejs.org/api/interfaces/routeroptions
  history: base => import.meta.client ? createMemoryHistory(base) : null, /* default */
} satisfies RouterConfig

On this page