Vue – Error: Redirected from “/login” to “/” via a navigation guard.

2020-06-01 1,654 0

Vue-Router 3.1.0+ push/replace cause NavigationDuplicated error (In a Promise)

问题还原

  • vue-router^3.1.0以后新版将$router.push/replace 升级为Promise回调,致使原本在Router.onError中监听的事件,执行到Promise.catch中了。如程序中没有catch()方法拦截则会直接报出异常。push在有第二第三个参数的时候不会返回Promise,否则onError会直接打印error
  • 低版本会提示 undefined 或者 name:NavigationDuplicated,高版本则类似为Error: Redirected from "/login" to "/" via a navigation guard.

解决方案

  • vue-router版本降级:^3.0.7以下
npm uninstall vue-router
npm install vue-router@3.0.7
  • 重写$router.push方法
import Router from 'vue-router'
//在引入Router之后重写
const originalPush = Router.prototype.push
Router.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)
}
  • 为每个router.push增加回调函数
router.push('/home').catch(err => {err})

参考

Vue 官方issues:https://github.com/vuejs/vue-router/issues/2881
ElementUI pull:https://github.com/ElemeFE/element/pull/17269
ElementUI issues:https://github.com/ElemeFE/element/issues/17044

相关文章

Vue – Fixed:router-view 切换跳转当前页面不刷新问题
Vue – Error: [vuex] unknown local mutation type: menu/SET_NAVMENU, global type: user/SET_NAVMENU