VueRouter.prototype.push 重写了原型上的push方法,统一的处理了错误信息

在vue项目中,如果使用$router.push跳转到一个相同的路由报错.

在vue-router在3.1.0版本之后,push和replace方法会返回一个promise对象,如果跳转到相同的路由,就报promise uncaught异常.

方案01-降版本

使用vue-router 3.1.0之前的版本就不会有这个错误。但是不推荐,因为这样就无法得到vue-router新版本提供的功能了。

方案2-使用catch捕获异常

在使用push或者replace的时候,需要使用catch来处理异常

// 在使用push的时候,需要使用catch来处理可能出现的异常this.$router.push('/login').catch(err=>{})

缺点:在使用push的时候,都需要使用catch处理

方案3-修改push方法

在router/index.js导入VueRouter的时候,进行全局的处理

const routerPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch((error) => error);
};

  

posted @ 2021-12-21 11:21  7c89  阅读(2693)  评论(0编辑  收藏  举报