vue-router重写push方法,解决相同路径跳转报错问题

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

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

由,就报promise uncaught异常.

为了避免这种报错可以通过修改vue-router的配置文件,默认位置router/index.js;配置方式如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

import Vue from 'vue'

import Router from 'vue-router'

  

/**

 * 重写路由的push方法

 * 解决,相同路由跳转时,报错

 * 添加,相同路由跳转时,触发watch (针对el-menu,仅限string方式传参,形如"view?id=5")

 */

  

// 保存原来的push函数

const routerPush = Router.prototype.push

// 重写push函数

Router.prototype.push = function push(location) {

  

 // 这个if语句在跳转相同路径的时候,在路径末尾添加新参数(一些随机数字)

 // 用来触发watch

 if(typeof(location)=="string"){

 var Separator = "&";

 if(location.indexOf('?')==-1) { Separator='?'; }

 location = location + Separator + "random=" + Math.random();

 }

  

 // 这个语句用来解决报错

 // 调用原来的push函数,并捕获异常

 return routerPush.call(this, location).catch(error => error)

}

  

Vue.use(Router)

export default new Router({

 routes: [

 {

  path: '/',

  

 }

 ]

})

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值