Nuxt 3 已于 31 July 2026 结束生命周期
此版本将不再接收错误修复或安全补丁。 升级到 Nuxt 4 或获取 HeroDevs 提供的延长支持

自定义路由

在 Nuxt 中,路由由 pages 目录下文件结构定义。然而,由于其底层使用了 vue-router,Nuxt 提供了多种方式在项目中添加自定义路由。

Geprüfte Übersetzung ·0 % geprüft

添加自定义路由

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

Router 配置

使用 router 选项,你可以选择通过一个接收扫描到的路由并返回自定义路由的函数,覆盖或扩展现有路由。

如果该函数返回 null 或 undefined,Nuxt 将回退使用默认路由(这在修改输入数组时很有用)。

app/router.options.ts
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 不会使用你提供的组件中 definePageMeta 定义的元数据,来扩展你从 routes 函数返回的任何新路由。如果你希望实现这一点,应使用 pages:extend 钩子,该钩子会在构建时调用。

Pages 钩子

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

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

nuxt.config.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 提供了几种添加路由的方式:

Router 选项

除了自定义 vue-router 的选项外,Nuxt 还提供了额外选项来自定义 Router。

使用 app/router.options

这是指定 router 选项的推荐方式。

app/router.options.ts
import type { RouterConfig } from '@nuxt/schema'

export default {
} satisfies RouterConfig

你可以通过 pages:routerOptions 钩子添加更多 Router 选项文件。数组中后面的项会覆盖前面的。

在此钩子中添加 router options 文件将启用基于页面的路由,除非设置了 optional,此时仅当基于页面的路由已启用时才会应用。
nuxt.config.ts
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
nuxt.config
export default defineNuxtConfig({
  router: {
    options: {},
  },
})

Hash 模式(SPA)

你可以使用 hashMode 配置在 SPA 模式下启用哈希历史记录。在此模式下,Router 会在实际 URL 前添加一个井号(#),并在内部传递该 URL。启用后,URL 永远不会发送到服务器,并且不支持 SSR。

nuxt.config.ts
export default defineNuxtConfig({
  ssr: false,
  router: {
    options: {
      hashMode: true,
    },
  },
})

针对哈希链接的滚动行为

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

nuxt.config.ts
export default defineNuxtConfig({
  router: {
    options: {
      scrollBehaviorType: 'smooth',
    },
  },
})

自定义 History(高级)

你还可以通过传入一个接收基础 URL 并返回历史模式的函数来覆盖历史模式。如果返回 null 或 undefined,Nuxt 会回退使用默认历史模式。

app/router.options.ts
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