错误说明

在vue项目中,如果使用$router.push跳转到一个相同的路由,就会遇到以下错误。
在这里插入图片描述

原因分析

vue-router3.1.0版本之后,pushreplace方法会返回一个promise对象,如果跳转到相同的路由,就报promise uncaught异常
可以参考:vue-router releases
在这里插入图片描述

解决方案

方案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的时候,进行全局的处理

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
// 重写了原型上的push方法,统一的处理了错误信息
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
Logo

前往低代码交流专区

更多推荐