问题描述

在升级了Vue-Router版本到到3.1.0及以上之后,页面在跳转路由控制台会报Uncaught (in promise) Error的问题 

Vue更新日志

https://github.com/vuejs/vue-router/releases 

V3.1.0版本里面新增功能:push和replace方法会返回一个promise, 你可能在控制台看到未捕获的异常

问题分析

解释:没有捕获异常。 

解决方案 

方法一: 检查代码

1、首先检查router.js中的路由path和name是否有误

2、查看main.js中的路由beforeEach导航守卫的路由跳转是否写错。

方法二:回退版本

在项目目录下运行

npm i vue-router@3.0 -S 

将vue-router改为3.0版本即可; 

方法三:捕获异常

1、在调用方法的时候用catch捕获异常 

this.$router.replace({ name: 'foo' }).catch(err => {
   console.log('all good')
})    

2、对Router原型链上的push、replace方法进行重写,这样就不用每次调用方法都要加上catch。

这个方法是vue-router的issues里面的一位大佬解决的

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
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)
}

 replace方法同上

// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace (location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

 

参考文章

https://blog.csdn.net/haidong55/article/details/100939076

https://forum.vuejs.org/t/topic/97260

https://www.cnblogs.com/xinheng/p/13019818.html

https://blog.csdn.net/ShIcily/article/details/102668403

https://blog.csdn.net/sunrj_niu/article/details/106902138

https://blog.csdn.net/Jone_hui/article/details/107411530

https://blog.csdn.net/qq_37875903/article/details/107494973

https://segmentfault.com/q/1010000019723749

Logo

前往低代码交流专区

更多推荐