vue-cli3中,重复点击同一个标签实现路由跳转,出现Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation

    技术2022-07-15  48

    目录

    1 错误

    2 原因

    3 解决方法

    1 错误

    vue中,连续多次单击同一个路由标签(单击该标签会发生路由跳转)跳转路由时,出现Uncaught (in promise)错误。

    如:上代码以及图如下

    <template> <div class = "footerGuideStyle"> <a href="javascript:;" class = "footerItems" v-bind:class = "{on: isPath('/msite')}" v-on:click = "goTo('/msite')"> <span> <i class = "iconfont icon-waimai"></i> </span> <span>首页</span> </a> <a href="javascript:;" class = "footerItems" :class = "{on: isPath('/search')}" @click = "goTo('/search')"> <span> <i class = "iconfont icon-fangdajing"></i> </span> <span>搜索</span> </a> <a href="javascript:;" class = "footerItems" :class = "{on: isPath('/order')}" @click = "goTo('/order')"> <span> <i class = "iconfont icon-order_icon"></i> </span> <span>订单</span> </a> <a href="javascript:;" class = "footerItems" :class = "{on: isPath('/profile')}" @click = "goTo('/profile')"> <span> <i class = "iconfont icon-gerenzhongxin1" ></i> </span> <span>个人中心</span> </a> </div> </template> <script> export default { methods:{ isPath: function (path) { return this.$route.path === path }, goTo: function (path) { this.$router.replace(path) } } } </script> <style lang="stylus" rel="stylesheet/stylus"> @import "../../common/stylus/mixins.styl" .footerGuideStyle top-border-1px(#999999) // 引入一像素上边框(border-top: 1px solid #999999;) position fixed //固定定位在底部 left 0 right 0 bottom 0 width 100% height 3.2rem display: -webkit-flex;//弹性布局,实现分四列显示 display flex margin-bottom 0.2rem .footerItems display: -webkit-flex; display flex flex 1 flex-direction column justify-content center align-items center text-align center margin 0.5rem color #999999 .on //&指向父选择器 color #317ef3 span font-size 0.9rem .iconfont font-size 1.6rem </style>

    当我们连续多次单击个人中心时,会发生下图错误Uncaught (in promise)错误。

     

           下面这张图是2021年1月8号补充的

    2 原因

    在 Vue-Router3.1.0+,此时如果支持 Promise,router.push或 router.replace将返回一个 Promise。当我们在脚手架中使用this.$router.replace(path)进行路由跳转的时候,返回一个Promise对象,发生未捕获的异常。

    3 解决方法

    参考了网上许多帖子,有如下办法

    1)方法一:Vue-Router版本降级,就是用回以前的Vue-Router版本(这个我没有试过,不建议使用

    2)方法二:在使用Vue-Router中router.push或 router.replace时,使用catch捕获异常。这个的话,就是每次使用时,都需要在后面添加异常捕获,比较麻烦,而且容易漏添加。

    this.$router.replace(path).catch(err => { console.log(err) })

    3)方法三:对Vue-Router原型链上的router.push router.replace方法进行重写,这样就不用每次调用方法都要加上catch。(亲测有效,强烈建议)

    在main.j或者index.js中(选一个)添加以下代码。注意,因为我自己使用的是relplace方法,所以我对该方法进行了重写,如果使用push方法,请对push方法进行重写。

    import VueRouter from "vue-router" /*解决一下报错问题:下面三行语句解决报错问题 * Uncaught (in promise) NavigationDuplicated * {_name: “NavigationDuplicated”, name: "NavigationDuplic}的报错问*/ const originalPush = VueRouter.prototype.replace; VueRouter.prototype.replace = function replace(location) { return originalPush.call(this, location).catch(err => err) };

    参考:本文参考网上多篇文章,实测第三种方法

    百里于2020年7月2日

    如果有错,请您指出!如有侵权,请联系我删除!

     

    Processed: 0.018, SQL: 9