其他分享
首页 > 其他分享> > vue-router beforeEach出现死循环

vue-router beforeEach出现死循环

作者:互联网

vue router 在beforeEach处理登录出现问题

有问题代码如下:

router.beforeEach((to, from, next) => {
  
  let token = localStorage.getItem('token')
  if(token){
    next()
  }else{
    if(to.fullPath == '/'){
      next()
    } else{
      next({ path: '/login' })
      //next()
    }
  }

})

  

当未获取到token时候,需要进入到login页面,此时会一直出现死循环,报错如下

 

 

 原因:因为进入login页面时候,/login又会进入beforeEach里面,这样就造成了死循环

  

  解决方式如下:

let token = localStorage.getItem('token')
  if(token){
    next()
  }else{
    if(to.fullPath == '/'){
      next()
    } else if (to.fullPath == '/login'){
      next()
    }else{
      next({ path: '/login' })
      //next()
    }
  }

  

标签:vue,beforeEach,next,token,router,login,else,死循环
来源: https://www.cnblogs.com/willsoo/p/14777977.html