自定义路由

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

添加自定义路由

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

Router 配置

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

如果该函数返回 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 钩子

你可以使用 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/app/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 模式下启用 hash 历史模式。在此模式下,路由会在内部跳转前使用 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 并返回历史模式的函数来覆盖历史模式。如果返回 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 /* 默认 */
} satisfies RouterConfig