路由报错解决方法
前端小菜-贺俊兰 2020-08-21 vuepress
# 问题描述
在vue项目中路由跳转过程中浏览器会报Avoided redundant navigation to current location 这个错误
该报错不影响功能,不过一直出现红色错误容易影响我们心态,所以我们来解决这个问题
首先,我们来看看控制台显示的错误,如下:
NavigationDuplicated: Avoided redundant navigation to current location: "xxx".
# 解决办法
# vue
在vue项目中,我们只需要添加以下代码
import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// 解决路由访问重复时报错问题:
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
当修改了push方法不生效时,我们可以尝试修改replace方法:
const originalReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function replace(location) {
return originalReplace.call(this, location).catch(err => err);
}
1
2
3
4
2
3
4
# vuepress
当然,有时候在vuepress中,可能你在配置侧边栏后,也会因为配置的问题会导致重复进入同个路由, 这个时候我们也需要添加像上面一样的方法
首先我们先创建enhanceApp.js
.
├─.vuepress/
│ └─ enhanceApp.js
1
2
3
2
3
接着在文件中添加如下代码
import VueRouter from 'vue-router'
const originalReplace = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
return originalReplace.call(this, location).catch(err => err);
};
export default ({
Vue,
options,
router, // 当前应用的路由实例
siteData // 站点元数据
}) => {
try {
} catch (e) {
console.error(e.message)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19