vue路由跳转报错 Navigation cancelled from … to ... with a new navigation

1,515 阅读1分钟

这个错误是vue-router内部错误,没有进行catch处理,导致的编程式导航跳转问题,往同一地址跳转时会报错的情况。

在升级了Vue-Router版本到到3.1.0及以上之后,页面在跳转路由控制台会报Uncaught (in promise)的问题,在3.1.0版本里面新增功能:push和replace方法会返回一个promise, 你可能在控制台看到未捕获的异常。

方案一: 安装vue-router3.0以下版本👀

方案二: 针对于路由跳转相同的地址添加catch捕获一下异常:

this.$router.push(’/location’).catch(err => { console.log(err) })

方案三: 在main.js下注册一个全局函数即可 (注:此处理方案只针对于vue-router 3.0以上版本哈!!!)

// 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 => {return;})
}
// replace
VueRouter.prototype.replace = function replace (location, onResolve, onReject) {
  // if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}