最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Vue3路由守卫如何使用 router.beforeEach 实现全局前置守卫
时间:2026-08-12 12:47:49 编辑:袖梨 来源:一聚教程网
router.beforeEach可实现全局前置守卫,每次路由跳转前自动执行,用于登录校验与权限控制;接收to、from、next三参数,依据meta.requiresAuth等元信息判断是否放行或重定向至/login,须确保所有逻辑分支均调用next且避免重复调用。
直接用 router.beforeEach 就能实现全局前置守卫,它在每次路由跳转前自动执行,是做登录校验、权限控制最常用的方式。
核心写法和参数含义
注册守卫时传入一个回调函数,接收三个参数:
-
to:目标路由对象,含
path、name、meta等信息 - from:当前离开的路由对象
- next:必须调用的导航控制函数,决定是否放行或跳转
常见判断逻辑写法
通常结合路由元信息(meta)做条件判断,比如:
- 检查
to.meta.requiresAuth是否为true,再读取本地 token 或 store 状态 - 若未登录且目标页需要认证,调用
next('/login')或next({ name: 'Login' }) - 若已登录或无需认证,统一调用
next()放行 - 注意避免重复调用
next,所有分支都要覆盖到
典型使用示例
在 router.js 中配置:
router.beforeEach((to, from, next) => {const token = localStorage.getItem('token')if (to.meta.requiresAuth && !token) {next('/login')} else if (to.meta.roles && !token) {next('/login')} else if (to.meta.roles && token) {const userRole = JSON.parse(atob(token.split('.')[1])).roleif (!to.meta.roles.includes(userRole)) {next('/403')} else {next()}} else {next()}})
注意事项和易错点
几个关键细节容易出问题:
- 守卫中不能访问
this,它是纯函数式调用 - 异步操作(如请求用户信息)要用
async/await+next配合,不能漏掉next - 重定向到登录页时,要排除登录页自身,否则会无限循环:
if (to.name !== 'Login' && !token) -
next(false)可中断导航并停留在当前页,适合表单未保存等场景