defineNuxtRouteMiddleware

使用 DefineNuxtRouteMiddleware 辅助函数创建命名路由中间件。

路由中间件存储在 Nuxt 应用的 middleware/ 目录中(除非是 否则设置)。

¥Route middleware are stored in the middleware/ of your Nuxt application (unless set otherwise).

类型

¥Type

defineNuxtRouteMiddleware(middleware: RouteMiddleware) => RouteMiddleware

interface RouteMiddleware {
  (to: RouteLocationNormalized, from: RouteLocationNormalized): ReturnType<NavigationGuard>
}

参数

¥Parameters

middleware

  • 类型:RouteMiddleware

一个函数,以两个 Vue Router 的路由位置对象作为参数:下一个路由 to 为第一个,当前路由 from 为第二个。

¥A function that takes two Vue Router's route location objects as parameters: the next route to as the first, and the current route from as the second.

了解更多关于 Vue 路由文档RouteLocationNormalized 的可用属性。

¥Learn more about available properties of RouteLocationNormalized in the Vue Router docs.

示例

¥Examples

显示错误页面

¥Showing Error Page

你可以使用路由中间件抛出错误并显示有用的错误消息:

¥You can use route middleware to throw errors and show helpful error messages:

middleware/error.ts
export default defineNuxtRouteMiddleware((to) => {
  if (to.params.id === '1') {
    throw createError({ statusCode: 404, statusMessage: 'Page Not Found' })
  }
})

上述路由中间件会将用户重定向到 ~/error.vue 文件中定义的自定义错误页面,并公开从中间件传递的错误消息和代码。

¥The above route middleware will redirect a user to the custom error page defined in the ~/error.vue file, and expose the error message and code passed from the middleware.

重定向

¥Redirection

在路由中间件中结合使用 useStatenavigateTo 辅助函数,根据用户的身份验证状态将用户重定向到不同的路由:

¥Use useState in combination with navigateTo helper function inside the route middleware to redirect users to different routes based on their authentication status:

middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {
  const auth = useState('auth')

  if (!auth.value.isAuthenticated) {
    return navigateTo('/login')
  }

  if (to.path !== '/dashboard') {
    return navigateTo('/dashboard')
  }
})

navigateToabortNavigation 都是全局可用的辅助函数,你可以在 defineNuxtRouteMiddleware 内部使用它们。

¥Both navigateTo and abortNavigation are globally available helper functions that you can use inside defineNuxtRouteMiddleware.