Vue-Router给当前url添加参数时报错 Navigation Duplicated Avoided redundant navigation to current location

发现当动态修改当前页面的url中的query时会报错

是因为新创建的路由不能使用老路由的对象,而应该重新创建一个对象,以解决问题

报错内容

新老路由发生重复,停止跳转

image-20220423221245770

解决方法

// 首先获取当前url
const q = this.$route && this.$route.query
// 通过创建新的路由的方式来添加参数
this.$router.push({ query: Object.assign({ filename: '' }, q) })

原因

  • 查看Vue-Router的源码,发现其判断的是新老query对象是否完全一致。

  • 而当通过直接修改$route.query去变化页面的时候,将会使得老的query对象也会跟着一起改变,于是就会被报路由重复

  • Vue-Router的源码中关于新老的判断

    • function isSameRoute (a, b, onlyPath) {
        if (b === START) {
          return a === b
        } else if (!b) {
          return false
        } else if (a.path && b.path) {
          return a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && (onlyPath ||
            a.hash === b.hash &&
            isObjectEqual(a.query, b.query))
        } else if (a.name && b.name) {
          return (
            a.name === b.name &&
            (onlyPath || (
              a.hash === b.hash &&
            isObjectEqual(a.query, b.query) &&
            isObjectEqual(a.params, b.params))
            )
          )
        } else {
          return false
        }
      }
      
  • 关于路由更新的逻辑

    • if (
          isSameRoute(route, current) &&
          // in the case the route map has been dynamically appended to
          lastRouteIndex === lastCurrentIndex &&
          route.matched[lastRouteIndex] === current.matched[lastCurrentIndex]
        ) {
          this.ensureURL();
          if (route.hash) {
            handleScroll(this.router, current, route, false);
          }
          return abort(createNavigationDuplicatedError(current, route))
        }
      
    • abort(createNavigationDuplicatedError(current, route))处弹出报错

实战实例

<script>
mounted () {
    const q = this.$route && this.$route.query
    const fn = q && q.filename
    if (fn) {
      this.fileName = fn
      this.component = 'Viewer'
    } else {
      this.component = 'Editor'
      if (q.filename === undefined) { this.$router.push({ query: Object.assign({ filename: '' }, q) }) }
    }
  }
</script>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值