跳到主要内容

自定义路由

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

添加自定义路由

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

路由配置(Router Config)

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

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

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

Pages 钩子

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

例如,阻止为任何 .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 提供了几种添加路由 的方式:

路由选项

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

使用 router.options

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

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

export default {
} satisfies RouterConfig

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

在此钩子中添加路由选项文件会开启基于页面的路由,除非设置了 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: {},
  },
})
future.compatibilityVersion: 5 下,路由默认大小写敏感以匹配 Nitro。将 router.options.sensitive 设为 false 可退出此行为。

Hash 模式(SPA)

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

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

Hash 链接的滚动行为

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

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

自定义历史模式(进阶)

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

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