You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue2.x自定义reloadPage函数触发NavigationDuplicated报错如何解决?

问题原因

这个报错是Vue Router 3.1.0及以上版本的特性:$router.push、$router.replace方法改为返回Promise对象,当导航到当前已经处于的路径时,就会抛出NavigationDuplicated类型的错误,没有被Promise的catch捕获时就会在控制台抛出该异常。
你当前触发报错的核心原因是:你配置的根路径/对应的路由name恰好也是Idx,所以当你在name为Idx的路由下执行this.$router.push('/')时,本质是尝试重复导航到当前路由,因此触发错误。

修复方案

方案1:当前方法内临时捕获错误

直接给push方法加空的catch回调,捕获忽略重复导航的报错即可:

reloadPage() {
    if (this.$route.name == "Idx") {
        // 加catch捕获重复导航错误
        this.$router.push('/').catch(err => {})
        //console.log("test")
    } else {
        this.$router.go() // RELOAD THE PAGE TO OVERTAKE THE CHANGES
    }            
}

方案2:全局配置统一处理所有重复导航报错

在你初始化Vue Router的文件(一般是router/index.js)里,重写push和replace方法,全局统一捕获这类错误,不需要每个调用处都加catch:

import VueRouter from 'vue-router'

// 重写push方法
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

// 重写replace方法(如果有用到replace也可以加)
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}

额外逻辑校验

如果你的业务需求是name为Idx时跳转根路径,但根路径的路由name本身就是Idx,那这个跳转逻辑本身是无效的,属于冗余操作:

  • 如果确实需要在Idx路由下刷新页面,你可以把这个分支的逻辑也改成this.$router.go()
  • 如果确实需要跳转到不同的页面,你需要调整路由配置,确保根路径/对应的路由name不是Idx

内容的提问来源于stack exchange,提问作者Chris

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:45:05