Vue-router不允许导航到当前位置(/path)错误原因以及修复方式
目录
- 报错提示
- 错误原因
- 错误演示
- 解决方法
- 方法一
- 方法二
- 方法三
报错提示 Navigating to current location ("/path") is not allowed
![Vue-router不允许导航到当前位置(/path)错误原因以及修复方式](https://img.it610.com/image/info11/b0ec3bb5ae394d5bb261ce9a93dc5495.jpg)
文章图片
错误原因 控制台出现以上这种
Navigating to current location ("/path") is not allowed
时,是因为重复进入了相同路由。错误演示 为了演示报错,用
vue-cli
重新构建了一个新的项目,只编写了一个按钮
一个input
。code:
// 路由跳转代码export default {data() {return {routeName: ''}},methods: {gotoHandle() {this.$router.push({name: this.routeName})}}}
动图演示
![Vue-router不允许导航到当前位置(/path)错误原因以及修复方式](https://img.it610.com/image/info11/d7f4a648ecf84271bb655fb25e7f0eba.gif)
文章图片
在重复进入相同路由时(不论是通过路径,还是路由名称进入),会提示不允许导航到当前位置(
path
), 就像上面的例子进入路由名为About
的路由时,提示的是path: "/about"
,Navigating to current location ("/about") is not allowed。这是因为跳转的方法错误时,未捕获错误处理,因此直接输出了错误信息。解决方法
方法一
直接在跳转报错的那个地方加上
.catch(error => error)
export default {data() {return {routeName: ''}},methods: {gotoHandle() {this.$router.push({name: this.routeName}).catch(error => error)}}}
【Vue-router不允许导航到当前位置(/path)错误原因以及修复方式】
方法二
为跳转错误的方法全局加上错误捕获。
import VueRouter from 'vue-router'const routerPush = VueRouter.prototype.pushVueRouter.prototype.push = function (location) {return routerPush.call(this, location).catch(error => error)}
以上代码在
main.js
,或者router/index.js
下执行,以及new VueRouter
之前之后都一样。因为是重置的VueRouter
原型对象上的push
事件,给原型对象的push
事件添加上了捕获异常,所以会通过原型链改变所有相关对象。replace
方法重复跳转错误与上方类似,把push
改成replace
就好。方法三
此方法为建议方法,建议优化跳转逻辑,避免重复跳转相同路由。
到此这篇关于Vue-router不允许导航到当前位置(/path)错误原因以及修复方式的文章就介绍到这了,更多相关Vue-router 导航到当前位置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- IDEA|IDEA 创建工程
- 移动用户体验设计(底部导航)
- EXCEL的汽车导航-全能的GPS定位
- React|React Native创建TabBar和导航栏
- 解决edge 每次启动 都会新开一个360网址导航页
- Vue|vue-router 详解
- 导航栏设置
- vue-router|vue-router 由hash更换为history模式
- iOS|iOS 导航栏返回的奇怪上移动画的bug
- vite+vue3+vue-router项目中vue-router报错的问题