addRouteMiddleware
middleware/
目录中的导航守卫(除非是 set otherwise)。类型
¥Type
function addRouteMiddleware (name: string, middleware: RouteMiddleware, options?: AddRouteMiddlewareOptions): void
function addRouteMiddleware (middleware: RouteMiddleware): void
interface AddRouteMiddlewareOptions {
global?: boolean
}
参数
¥Parameters
name
- 类型:
string
|RouteMiddleware
可以是字符串或 RouteMiddleware
类型的函数。此外,由于内容已存在于 HTML 文档中,爬虫可以索引它而无需额外开销。
¥Can be either a string or a function of type RouteMiddleware
. Function takes the next route to
as the first argument and the current route from
as the second argument, both of which are Vue route objects.
了解更多关于 路由对象 的可用属性。
¥Learn more about available properties of route objects.
middleware
- 类型:
RouteMiddleware
第二个参数是一个 RouteMiddleware
类型的函数。与上文相同,它提供 to
和 from
路由对象。如果 addRouteMiddleware()
中的第一个参数已经作为函数传递,则它变为可选。
¥The second argument is a function of type RouteMiddleware
. Same as above, it provides to
and from
route objects. It becomes optional if the first argument in addRouteMiddleware()
is already passed as a function.
options
- 类型:
AddRouteMiddlewareOptions
可选的 options
参数允许你将 global
的值设置为 true
,以指示路由中间件是否为全局(默认设置为 false
)。
¥An optional options
argument lets you set the value of global
to true
to indicate whether the router middleware is global or not (set to false
by default).
示例
¥Examples
命名路由中间件
¥Named Route Middleware
命名路由中间件的定义方式为:第一个参数为字符串,第二个参数为函数:
¥Named route middleware is defined by providing a string as the first argument and a function as the second:
export default defineNuxtPlugin(() => {
addRouteMiddleware('named-middleware', () => {
console.log('named middleware added in Nuxt plugin')
})
})
在插件中定义时,它会覆盖 middleware/
目录中任何现有的同名中间件。
¥When defined in a plugin, it overrides any existing middleware of the same name located in the middleware/
directory.
全局路由中间件
¥Global Route Middleware
全局路由中间件,放置在 中,后缀为 ,并在每次路由更改时运行。
¥Global route middleware can be defined in two ways:
- 直接将函数作为第一个参数传递,无需指定名称。它将自动被视为全局中间件,并在每次路由更改时应用。plugins/my-plugin.ts
export default defineNuxtPlugin(() => { addRouteMiddleware((to, from) => { console.log('anonymous global middleware that runs on every route change') }) })
- 设置可选的第三个参数
{ global: true }
,以指示路由中间件是否为全局的。plugins/my-plugin.tsexport default defineNuxtPlugin(() => { addRouteMiddleware('global-middleware', (to, from) => { console.log('global middleware that runs on every route change') }, { global: true } ) })