解决Vue-router 报NavigationDuplicated的三种方法

控制台会报[NavigationDuplicated {_name: "NavigationDuplicated", name: "NavigationDuplicated"}]。其原因在于Vue-router在3.1之后把$router.push()方法改为了Promise。所以假如没有回调函数,错误信息就会交给全局的路由错误处理,因此就会报上述的错误。

vue-router是先报了一个Uncaught (in promise)的错误(因为push没加回调),然后再点击路由的时候才会触发NavigationDuplicated的错误(路由出现的错误,全局错误处理打印了出来)

方案1: 降版,固定vue-router版本到3.0.7以下。

npm i vue-router@3.0 -S

方案2: 禁止全局路由错误处理打印,这个个方法是vue-router的issues里面的一位大佬解决的

在引入 vue-router 的文件中增加以下代码,对Router原型链上的push、replace方法进行重写,这样就不用每次调用方法都要加上catch:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

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)
}

方案3: 为每一个增加回调函数,vue-router的开发者给出了解决方法

posted @ 2020-12-25 10:47  Leise  阅读(1814)  评论(0编辑  收藏  举报