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

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

目录

报错提示

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})
    }
  }
}

动图演示

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

转载请保留出处和原文链接:https://www.cnhackhy.com/81699.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部