nuxt logo

文档翻译(非官方)

Nuxt.js
Version:v3.17

自定义路由

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

添加自定义路由

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

路由配置

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

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

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

export default {
  // https://router.vuejs.org/api/interfaces/routeroptions.html#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 提供了额外的选项来自定义路由器。

使用 app/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/app/router-options'),
        optional: true
      })
    }
  }
})

使用 nuxt.config

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

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

哈希模式 (SPA)

你可以使用 hashMode 配置在 SPA 模式下启用哈希历史。在这种模式下,路由器在实际 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'
    }
  }
})

自定义历史记录(高级)

你可以选择使用一个函数来覆盖历史模式,该函数接受基本 URL 并返回历史模式。如果返回 nullundefined,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.html
  history: base => import.meta.client ? createMemoryHistory(base) : null /* default */
} satisfies RouterConfig