解决 Vue-Router 升级导致的 Uncaught (in promise) 问题

解决 Vue-Router 升级导致的 Uncaught (in promise) 问题

在 Vue-Router 升级到 3.1.0 之后,push 和 replace 方法会返回一个 promise,你可能在控制台看到未捕获的异常。这只是编程式导航才会出现的问题

此前版本没有报错的原因是 vue-router 没有返回错误信息,所以我们一直无法捕获,并非异常不存在,反正现在就是能够捕获了

既然返回的是一个 promise 的话,那么用 catch 捕获就好了

// 这两个变量是备份,因为可以看出下面是修改了原型上的方法,并没有修改这两个变量
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
//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
VueRouter.prototype.replace = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}

参考链接:http://news.558idc.com/14100.html

posted @ 2022-08-10 17:24  朱在春  阅读(345)  评论(0编辑  收藏  举报