路由中间件类似路由守卫,即在导航到特定路由之前运行一段代码

内联路由中间件

在页面中定义的路由中间件,因没有名称,所以也叫匿名路由中间件

definePageMeta({
  middleware: [
    function (to, from) {
      console.log("执行了内联路由中间件", to, from);
    },
  ],
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.

命名路由中间件

在 middleware 目录中定义,如 middleware/routerInfo.ts

export default defineNuxtRouteMiddleware((to, from) => {
  console.log("路由信息 from --", from);
  console.log("路由信息 to --", to);
});
  • 1.
  • 2.
  • 3.
  • 4.

在页面中使用

definePageMeta({
  middleware: ["router-info"],
  // 或 middleware: 'router-info'
});
  • 1.
  • 2.
  • 3.
  • 4.

路由中间件的名称会被规范化为 kebab-case 格式:myMiddleware 变成 my-middleware。

全局路由中间件

每次路由更改时都运行

通过添加 .global 后缀实现,如 middleware/routerInfo.global.ts

路由中间件的返回值

照常路由

无返回值时,即按原计划完成路由导航

路由重定向

// 重定向到 /about
return navigateTo('/about')
  • 1.
  • 2.

重定向到给定的路径,并在服务器端发生重定向时设置重定向代码为 301

return navigateTo('/', { redirectCode: 301 })
  • 1.

中断路由

return abortNavigation()
// 中止路由时提供错误消息
return abortNavigation(error)
  • 1.
  • 2.
  • 3.

路由中间件的执行顺序

1. 全局路由中间件

默认按全局路由文件名的字符串顺序

Nuxt3【路由中间件】middleware_文件名


middleware/my.global.ts 会先执行

若想让 middleware/routerInfo.global.ts 先执行,可在文件名前加数字前缀,如

Nuxt3【路由中间件】middleware_middleware_02


注意事项:

Nuxt3【路由中间件】middleware_重定向_03

虽然目录中 2.my.global.ts 在上面,但 10.routerInfo.global.ts 会先执行,因为是按文件名的字符串顺序执行,所以个位数需加前缀 0,即 01 ,02

2. 页面中定义的中间件

按数组的顺序

definePageMeta({
  middleware: [
    function (to, from) {
      // 自定义内联中间件
    },
    'demo2',
    'demo1',
  ],
});
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

即先执行匿名中间件,然后是 demo2,最后是 demo1

路由中间件的执行时机

默认情况下,因是服务器渲染,路由中间件在服务端渲染时会执行一次,在客户端渲染时,又会执行一次!

通过下方代码,可以精确自定义路由中间件的执行时机:

export default defineNuxtRouteMiddleware(to => {
  // 在服务器端跳过中间件
  if (process.server) return
  // 完全在客户端跳过中间件
  if (process.client) return
  // 或仅在初始客户端加载时跳过中间件
  const nuxtApp = useNuxtApp()
  if (process.client && nuxtApp.isHydrating && nuxtApp.payload.serverRendered) return
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

动态添加中间件

使用 addRouteMiddleware() 辅助函数手动添加全局或命名的路由中间件,比如在插件中添加。

export default defineNuxtPlugin(() => {
  addRouteMiddleware('global-test', () => {
    console.log('这个全局中间件是在插件中添加的,将在每次路由更改时运行')
  }, { global: true })

  addRouteMiddleware('named-test', () => {
    console.log('这个命名中间件是在插件中添加的,将覆盖同名的任何现有中间件')
  })
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.