自定义路由
添加自定义路由
在 Nuxt 中,路由是由 app/pages 目录 下的文件结构定义的。然而,由于其底层使用Vue Router底层使用 vue-router,Nuxt 提供了多种在项目中添加自定义路由的方法。
路由配置 (Router Config)
通过 router 选项,你可以选择通过一个函数来覆盖或扩展路由,该函数接收扫描到的路由并返回自定义后的路由。
如果返回 null 或 undefined,Nuxt 将回退到默认路由(适用于修改输入数组)。
import type { RouterConfig } from '@nuxt/schema'
export default {
// https://router.vuejs.ac.cn/api/interfaces/routeroptions#routes
routes: _routes => [
{
name: 'home',
path: '/',
component: () => import('~/pages/home.vue'),
},
],
} satisfies RouterConfig
Pages 钩子
你可以使用 pages:extend Nuxt 钩子来添加、更改或删除扫描到的路由中的页面。
例如,若要防止为任何 .ts 文件创建路由
import type { NuxtPage } from '@nuxt/schema'
export default defineNuxtConfig({
hooks: {
'pages:extend' (pages) {
// add a route
pages.push({
name: 'profile',
path: '/profile',
file: '~/extra-pages/profile.vue',
})
// remove routes
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 模块。
extendPages(callback: pages => void)extendRouteRules(route: string, rule: NitroRouteConfig, options: ExtendRouteRulesOptions)
路由选项
除了自定义选项之外Vue Router,Nuxt 还提供了 其他选项 来自定义路由器。
使用 router.options
这是指定 路由选项 的推荐方式。
import type { RouterConfig } from '@nuxt/schema'
export default {
} satisfies RouterConfig
可以通过在 pages:routerOptions 钩子中添加文件来增加更多的路由器选项文件。数组中靠后的项会覆盖靠前的项。
optional,在这种情况下,它仅在已启用基于页面的路由时才生效。import { createResolver } from '@nuxt/kit'
export default defineNuxtConfig({
hooks: {
'pages:routerOptions' ({ files }) {
const resolver = createResolver(import.meta.url)
// add a route
files.push({
path: resolver.resolve('./runtime/router-options'),
optional: true,
})
},
},
})
使用 nuxt.config
注意: 只有可 JSON 序列化的 选项 是可配置的
linkActiveClasslinkExactActiveClassendsensitivestricthashModescrollBehaviorType
export default defineNuxtConfig({
router: {
options: {},
},
})
Hash 模式 (SPA)
你可以在 SPA 模式下使用 hashMode 配置 启用 hash 历史记录。在此模式下,路由器会在实际传递的 URL 之前使用一个 hash 字符 (#)。启用此功能后,URL 不会发送到服务器,且不支持 SSR。
export default defineNuxtConfig({
ssr: false,
router: {
options: {
hashMode: true,
},
},
})
Hash 链接的滚动行为
你可以选择自定义 hash 链接的滚动行为。当你将 配置 设置为 smooth,并加载带有 hash 链接的页面(例如 https://example.com/blog/my-article#comments)时,浏览器会平滑滚动到该锚点。
export default defineNuxtConfig({
router: {
options: {
scrollBehaviorType: 'smooth',
},
},
})
自定义历史记录 (高级)
你可以选择通过一个函数覆盖历史模式,该函数接收基础 URL 并返回历史模式。如果它返回 null 或 undefined,Nuxt 将回退到默认历史模式。
import type { RouterConfig } from '@nuxt/schema'
import { createMemoryHistory } from 'vue-router'
export default {
// https://router.vuejs.ac.cn/api/interfaces/routeroptions
history: base => import.meta.client ? createMemoryHistory(base) : null, /* default */
} satisfies RouterConfig