自定义路由

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

Geprüfte Übersetzung ·0 % geprüft

添加自定义路由

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

路由配置

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

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

页面钩子

你可以使用 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 提供了几种添加路由的方法:

Router 选项

除了自定义 vue-router 的选项外,Nuxt 还提供了其他选项来自定义路由器。

使用 router.options

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

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

export default {
} satisfies RouterConfig

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

在此钩子中添加路由选项文件会启用基于页面的路由,除非将 optional 设置为 true,此时只有在已启用基于页面的路由时才会应用该文件。
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 即可选择退出。

忽略大小写路由下的路由规则

除非 router.options.sensitive 为 true,否则 Nuxt 会将请求路径和规则模式都转换为小写,再匹配路由规则。模式中的正则约束会保持原样,因此必须按小写字母编写:/products/:id([a-z0-9]+) 可以匹配 /Products/ABC1。

如果约束能匹配大写字母却不能匹配其小写形式(例如 [A-Z]、\x41 或 (?:FOO)),或者是只排除其中一种形式的否定字符类(例如 [^a-z]),构建会失败。请改用 [a-z] 或 [^a-zA-Z]。如果 nuxt.config 中的 sensitive 为 true,或在 app/router.options.ts 中进行了设置,则会在应用加载时执行检查;除非 sensitive 为 true,否则应用会抛出错误。

Hash 模式(SPA)

你可以使用 hashMode 配置在 SPA 模式下启用 hash 历史记录。在此模式下,路由器会在实际 URL 前使用一个井号(#),并在内部传递该 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',
    },
  },
})

自定义 History(高级)

你可以选择使用一个接收基准 URL 并返回 history 模式的函数来覆盖 history 模式。如果它返回 null 或 undefined,Nuxt 将回退到默认 history。

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, /* 默认 */
} satisfies RouterConfig