Vue-router不允许导航到当前位置(/path)错误原因以及修复方式

目录

  • 报错提示
  • 错误原因
  • 错误演示
  • 解决方法
    • 方法一
    • 方法二
    • 方法三

报错提示 Navigating to current location ("/path") is not allowed

Vue-router不允许导航到当前位置(/path)错误原因以及修复方式
文章图片


错误原因 控制台出现以上这种 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)错误原因以及修复方式
文章图片


在重复进入相同路由时(不论是通过路径,还是路由名称进入),会提示不允许导航到当前位置(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 导航到当前位置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读