如何配置Vue路由多守卫,限制特定用户仅能访问指定路径避免死循环
你出现路由死循环的核心原因是调整逻辑时没有先判断当前目标路由是否为datacollector用户的可访问路径,导致跳转到达/datacollector后触发该路由绑定的guard守卫时,又重复执行跳转逻辑,形成无限循环。
按如下逻辑修改guard函数即可解决问题:
function guard (to, from, next) { // 未登录直接跳转登录页 const hasJwt = !!localStorage.getItem('jwt') if (!hasJwt) { next('/login') return } // 判断是否为datacollector类型用户 const isDatacollector = !!localStorage.getItem('datacollector') if (isDatacollector) { // 定义该类用户可访问的路径白名单 const allowPaths = ['/datacollector', '/logout'] // 目标路径在白名单内直接放行,避免循环 if (allowPaths.includes(to.path)) { next() } else { // 非白名单路径跳转到指定首页 next('/datacollector') } return } // 其余已登录用户正常放行 next() }
补充说明
- 该逻辑不会产生循环:当跳转到
/datacollector后再次触发guard时,会命中白名单判断直接放行,不会重复跳转 - 请提前配置
/logout对应的路由规则,避免该路径访问时匹配到404页 - 登录成功后的默认跳转可以在登录逻辑中补充判断:如果localStorage存在
datacollector字段,直接调用$router.push('/datacollector')即可
内容的提问来源于stack exchange,提问作者user15282016
相关产品推荐
相关产品推荐

