vue.js框架 Error: Avoided redundant navigation to current location

本文详细介绍了在使用ElementUI与vue-router 3.0以上版本时,遇到的重复点击菜单导致的报错问题及解决方案。通过在router/index.js中添加特定代码,可以有效避免此错误,确保应用程序的稳定运行。

1、ErrorCode:
在这里插入图片描述

2、原因:
ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题

3、解决办法(router --》index.js添加以下代码 ):
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
return originalPush.call(this, location).catch(err => err)
}

Vue.js 项目中使用 Vue Router 时,导航到当前位置时出现 `NavigationDuplicated` 错误,是因为 Vue Router 会阻止重复导航到当前路由,以避免不必要的操作和性能问题。以下是几种解决该问题的方法: ### 方法一:捕获并忽略错误 在 Vue Router 的实例中,重写 `push` 和 `replace` 方法,捕获 `NavigationDuplicated` 错误并忽略它。 ```javascript import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const originalPush = VueRouter.prototype.push; VueRouter.prototype.push = function push(location) { return originalPush.call(this, location).catch(err => { if (err.name !== 'NavigationDuplicated') throw err; }); }; const originalReplace = VueRouter.prototype.replace; VueRouter.prototype.replace = function replace(location) { return originalReplace.call(this, location).catch(err => { if (err.name !== 'NavigationDuplicated') throw err; }); }; const router = new VueRouter({ routes: [ // 路由配置 ] }); export default router; ``` ### 方法二:在导航前检查当前路由 在进行导航操作之前,先检查当前路由是否与目标路由相同,如果相同则不进行导航。 ```javascript // 在组件中使用 this.$router.currentRoute.path === '/home' ? null : this.$router.push('/home'); // 在函数中使用 function navigateToHome(router) { if (router.currentRoute.path !== '/home') { router.push('/home'); } } ``` ### 方法三:使用 `catch` 捕获错误 在每次调用 `push` 或 `replace` 方法时,使用 `catch` 方法捕获 `NavigationDuplicated` 错误。 ```javascript this.$router.push('/home').catch(err => { if (err.name === 'NavigationDuplicated') { // 忽略错误 } else { // 处理其他错误 console.error(err); } }); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值