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

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Vue-router不允许导航到当前位置(/path)错误原因以及修复方式脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

报错提示

Navigating to current location ("/path") is not Allowed

Navigating to current location ("/path") is not allowed

错误原因

控制台出现以上这种 Navigating to current location ("/path") is not allowed 时,是因为重复进入了相同路由。

错误演示

为了演示报错,用vue-cli重新构建了一个新的项目,只编写了一个按钮一个input
code:

<!-- vue模板代码 -->
<div>
	<button @click="gotoHandle">测试路由跳转</button>
	<input v-model="routeName">
<div>
// 路由跳转代码
export default {
  data() {
    return {
      routeName: ''
    }
  },
  methods: {
    gotoHandle() {
      this.$router.push({name: this.routeName})
    }
  }
}

动图演示

Navigating to current location ("/path") is not allowed

在重复进入相同路由时(不论是通过路径,还是路由名称进入),会提示不允许导航到当前位置(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)
    }
  }
}

方法二

为跳转错误的方法全局加上错误捕获。

import VueRouter From 'vue-router'

const routerPush = VueRouter.PRototyPE.push
VueRouter.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 导航到当前位置内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的Vue-router不允许导航到当前位置(/path)错误原因以及修复方式全部内容,希望文章能够帮你解决Vue-router不允许导航到当前位置(/path)错误原因以及修复方式所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Vue-router