【vue-router】Error: Redirected when going from “/login?redirect=%2Fxxx“ to “/xxx“

346 阅读1分钟

报错场景

用户退出-> 重新登陆 -> 指定跳转到退出的页面

报错原因

新版的vue-router返回的是promiss对象

permission.js里的指定跳转页面方法 next({ ...to, replace: true })会被认为是一个失败的navigation(虽然能导航成功,但不再是原来的to),所以login里的push()返回一个rejected Promise

解决思路

捕捉到报错

解决方法

  1. login.vue页面捕捉错误

this.$router.push(query.redirect || "/").catch(() => {})

2.在全局permission.js捕捉错误


const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject)
    return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch((err) => err);
};