zoukankan      html  css  js  c++  java
  • Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/xxx". at createRouterError 的说明和解决

    错误说明

    Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/xxx". at createRouterError
    这个错误是说着在promise里捕获了一个导航的重复定义,因为这里是使用编程式导航去进行路由跳转的,$router.push方法会返回一个promise对象。在这里重复的push了同一个路由地址,所以就报了这个错误。
    有时也会报这个错Uncaught (in promise) Error: Navigation cancelled from "/xxx" to "/xxx" with a new navigation

    具体例子可看下面。

    错误定位

    <template>
      <div @click="toDetail(item.articleId)">
        <el-button @click="toDetail(item.articleId)">阅读</el-button>
      </div>
    </template>
    
    <script>
    export default{
      methods:{
        toDetail(id) {
          this.$router.push({ name: 'detail', params: { articleId: id } })
        }
      }
    }
    </script>
    

    因为el-button是在div里的,所按钮点击的时候会有两个click都调用了相同的push

    错误解决

    方法一

    把嵌套的子元素中的触发路由的事件去掉,这里把el-button中的click去掉就行了。

    方法二

    因为这个错误是在push中抛出的,所以在其中捕获catch这个错误就行了,不过这似乎是个治标不治本的办法,所有在push中的错误都可以用此法捕获。
    在路由中,添加如下代码进行配置:

    import Vue from 'vue'
    import VueRouter from 'vue-router'
    
    Vue.use(VueRouter)
    
    // 捕获push replace中的错误
    // 当然在replace中的错误也是可以相同的进行捕获
    const originalPush = VueRouter.prototype.push
    const originalReplace = VueRouter.prototype.replace
    // 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
    VueRouter.prototype.replace = function push(location, onResolve, onReject) {
      if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
      return originalReplace.call(this, location).catch(err => err)
    }
    
  • 相关阅读:
    tyvj1463 智商问题
    P1070 道路游戏
    P1862 输油管道问题
    P1875 佳佳的魔法药水
    P1498 南蛮图腾
    P1489 猫狗大战
    P1395 会议(求树的重心)
    P2285 [HNOI2004]打鼹鼠
    P3819 松江1843路(洛谷月赛)
    P3818 小A和uim之大逃离 II(洛谷月赛)
  • 原文地址:https://www.cnblogs.com/flytree/p/14669009.html
Copyright © 2011-2022 走看看