自定义路由
添加自定义路由
¥Adding custom routes
在 Nuxt 中,你的路由由 页面目录 内文件的结构定义。但是,由于 Nuxt 内部使用了 vue-router,因此它提供了几种在项目中添加自定义路由的方法。
¥In Nuxt, your routing is defined by the structure of your files inside the pages directory. However, since it uses vue-router under the hood, Nuxt offers you several ways to add custom routes in your project.
路由配置
¥Router Config
使用 路由选项,你可以选择使用接受扫描到的路由并返回自定义路由的函数来覆盖或扩展路由。
¥Using router options, you can optionally override or extend your routes using a function that accepts the scanned routes and returns customized routes.
如果返回 null
或 undefined
,Nuxt 将回退到默认路由(用于修改输入数组)。
¥If it returns null
or undefined
, Nuxt will fall back to the default routes (useful to modify input array).
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
definePageMeta
中定义的元数据来扩展你从 routes
函数返回的任何新路由。如果你希望这样做,你应该使用 pages:extend
钩子,即 called at build-time。页面钩子
¥Pages Hook
你可以使用 pages:extend
Nuxt 钩子从扫描的路由中添加、更改或删除页面。
¥You can add, change or remove pages from the scanned routes with the pages:extend
nuxt hook.
例如,要阻止为任何 .ts
文件创建路由:
¥For example, to prevent creating routes for any .ts
files:
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 Module
如果你计划添加与特定功能相关的整套页面,则可能需要使用 Nuxt 模块。
¥If you plan to add a whole set of pages related with a specific functionality, you might want to use a Nuxt module.
¥The Nuxt kit provides a few ways to add routes:
extendPages
(回调:pages => void)extendRouteRules
(route:string,rule:NitroRouteConfig,options:ExtendRouteRulesOptions)
路由选项
¥Router Options
除了自定义 vue-router
选项之外,Nuxt 还提供 附加选项 来自定义路由。
¥On top of customizing options for vue-router
, Nuxt offers additional options to customize the router.
app/router.options
使用
¥Using app/router.options
这是指定 路由选项 的推荐方法。
¥This is the recommended way to specify router options.
import type { RouterConfig } from '@nuxt/schema'
export default {
} satisfies RouterConfig
可以通过在 pages:routerOptions
钩子中添加文件来添加更多路由选项文件。数组中后面的项会覆盖前面的项。
¥It is possible to add more router options files by adding files within the pages:routerOptions
hook. Later items in the array override earlier ones.
optional
,在这种情况下,它仅在已启用基于页面的路由时才适用。¥Adding a router options file in this hook will switch on page-based routing, unless optional
is set, in which case it will only apply when page-based routing is already enabled.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/app/router-options'),
optional: true
})
}
}
})
nuxt.config
使用
¥Using nuxt.config
注意:只有 JSON 可序列化的 options 是可配置的:
¥Note: Only JSON serializable options are configurable:
linkActiveClass
linkExactActiveClass
end
sensitive
strict
hashMode
scrollBehaviorType
export default defineNuxtConfig({
router: {
options: {}
}
})
哈希模式 (SPA)
¥Hash Mode (SPA)
你可以使用 hashMode
config 在 SPA 模式下启用哈希历史记录。在此模式下,路由在内部传递的实际 URL 前使用井号 (#)。启用后,URL 永远不会发送到服务器,并且不支持 SSR。
¥You can enable hash history in SPA mode using the hashMode
config. In this mode, router uses a hash character (#) before the actual URL that is internally passed. When enabled, the URL is never sent to the server and SSR is not supported.
export default defineNuxtConfig({
ssr: false,
router: {
options: {
hashMode: true
}
}
})
哈希链接的滚动行为
¥Scroll Behavior for hash links
你可以选择自定义哈希链接的滚动行为。当你将 config 设置为 smooth
并加载带有哈希链接的页面(例如 https://example.com/blog/my-article#comments
)时,你将看到浏览器平滑地滚动到此锚点。
¥You can optionally customize the scroll behavior for hash links. When you set the config to be smooth
and you load a page with a hash link (e.g. https://example.com/blog/my-article#comments
), you will see that the browser smoothly scrolls to this anchor.
export default defineNuxtConfig({
router: {
options: {
scrollBehaviorType: 'smooth'
}
}
})
自定义历史记录(高级)
¥Custom History (advanced)
你可以选择使用一个接受基本 URL 并返回历史模式的函数来覆盖历史模式。如果返回 null
或 undefined
,Nuxt 将回退到默认历史记录。
¥You can optionally override history mode using a function that accepts the base URL and returns the history mode. If it returns null
or undefined
, Nuxt will fallback to the default history.
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