解决Vue中路由跳转后地址和代码中的不一样且不跳转,网页卡死,Cpu爆满

做项目的时候遇到了一个问题

vue在路由跳转的时候莫名其妙cpu爆满,网页直接卡死。而且地址栏跳转的路径也不对,代码如下

router.beforeEach((to, from, next) => {
  const role = JSON.parse(localStorage.getItem("user"));
  console.log(role);
  if(to.fullPath === '/exit'){
    localStorage.removeItem("user");
    next({path: 'login'})
  }else if(to.matched.length === 0){
    next({
      path: '404'
    })
  } else if (to.meta.requireAuth) {
    if (store.state.user.username) {
      if (to.meta.permission) {
          // 如果是管理员权限则可进入
          role.username === 'admin'
              ? next()
              : next('403');
        }
      next()
    } else {
      ElMessage.error('请登录');
      next({
        path: 'login',
        query: {redirect: to.fullPath}
      })
    }
  }  else {
    next()
  }
}

 

后来经过很长时间的调试,发现整个循环判断执行了两次,且第二次要跳转的路由地址是直接把我/(反斜杠)后面的路径变成要跳转的路径了,

并没有变换整个路径

if(to.fullPath === '/exit'){
    localStorage.removeItem("user");
    next({path: 'login'})
  }

 

解决办法:

在next中的path里面加上/(反斜杠)后再加要跳转的路径,代码如下

router.beforeEach((to, from, next) => {
  const role = JSON.parse(localStorage.getItem("user"));
  console.log(role);
  if(to.fullPath === '/exit'){
    localStorage.removeItem("user");
    next({path: '/login'})
  }else if(to.matched.length === 0){
    next({
      path: '/404'
    })
  } else if (to.meta.requireAuth) {
    if (store.state.user.username) {
      if (to.meta.permission) {
          // 如果是管理员权限则可进入
          role.username === 'admin'
              ? next()
              : next('/403');
        }
      next()
    } else {
      ElMessage.error('请登录');
      next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    }
  }  else {
    next()
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值