vue-router中重写push方法

发布时间 2023-11-07 10:32:02作者: 崛起崛起

文章目的:

看到一段代码不理解什么意思,查了一下是为了解决,重复跳转相同的路由,控制台报错。 重写了方法后,能catch异常,不会在控制台报错了。

代码:

Router.prototype.push = function push(location) {
    console.log(location, 'location')
    return routerPush.call(this, location).catch(error => error)
}

解释:

写完路由重复点击路由两次,控制台上就会报错:如上图所示

解决它:代码如下

点击跳转同一个路径
在VueRouter上配置路由跳转,在router中的index.js中加上以下代码,注意加在use之前

import Vue from 'vue'
import VueRouter from 'vue-router'
 
// 解决路由重复跳转错误
const routerPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
    return routerPush.call(this, location).catch(err => { })
};
 
Vue.use(VueRouter)