vue中beforeEach在使用遇到的一个死循环;

在做vue项目时,写了如下代码,页面卡死,出现死循环,可能是逻辑有问题,大佬给理理

相关代码

mounted() {

console.log("aaa")
let _this = this
this.$router.beforeEach(function (to,from,next) {
  if(to.meta.auth) {
    if(window.localStorage.getItem('user')) {
      console.log('路由设置了守卫,但是已经登录了');
      next()
    } else {
      console.log('路由设置了守卫,但是我还没有登录')
      console.log(_this.$router, 'sfafasdfasdf')
      _this.$router.push({path:'/login'})
      next({
        path: to.path,
      })
    } 
  } else {
    console.log("路由没有设置守卫");
    next({
      path: to.path
    })
  }
}) 

}

我想在设置了守卫的路由上,进行登录后再跳转到用户之前想看的页面

阅读 3.5k
4 个回答

你这就一直登陆跳登陆嘛,你要当to.path!='/login'并且没有登陆的时候跳登陆啊。

图片描述

      _this.$router.push({path:'/login'})
      next({
        path: to.path,
      })

改为

  next({
    path: ‘/login’,
  })
this.$router.beforeEach(function (to, from, next) {
  if (to.meta.auth) {
    if (window.localStorage.getItem('user')) {
      console.log('路由设置了守卫,但是已经登录了');
      next()
    } else {
      console.log('路由设置了守卫,但是我还没有登录')
      next({path: '/login'})
    }
  } else {
    console.log("路由没有设置守卫");
    next()
  }
})  
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题