vue-router 3.1.6,.push相同路径时报错的问题 Uncaught(in Promise)

一、问题描述

使用vue-router跳转相同路由的时,比如在 /defend 路由下,使用 this.$router.push('/defend')再次跳转当前路由,控制台会报以下错误。
简单的意思就是:导航重复了(NavigatingDuplicated),message中也说了,不允许导航到当前位置(Navigating to current location ("/defend") is not allowed),话说我之前路由没有这个问题啊?

Uncaught (in promise)
NavigationDuplicated {_name: "NavigationDuplicated", name: "NavigationDuplicated", message: "Navigating to current location ("/defend") is not allowed", stack: "Error↵ at new NavigationDuplicated (webpack-int…node_modules/vue/dist/vue.runtime.esm.js:2178:14)"}
在这里插入图片描述

二、解决问题
  1. 出现问题的原因
    老项目没有这个问题,新项目突然路由跳转出现了报错,首先看了一下新项目package.json中的vue-router的版本号 3.1.6,掐指一算,可能是路由更新导致的。
  2. 解决:知道问题的原因了,那么就想办法呗

    • 将vue-router回退到老版本
    • 重写vue-router的push方法
  3. 重写
    我是在main.ts文件中重写的
import Vue from 'vue'
import App from './App'
import Router from 'vue-router';

// 解决 vue-router 3.1.0+路由,重新进入相同路由时报错的问题 Uncaught(in Promise)
const VueRouterPush = Router.prototype.push;
Router.prototype.push = function push(toLocation: 'string') {
    return (VueRouterPush.call(this, toLocation) as any).catch((err: any) => err)
}

最后,解决了我目前路由跳转当前页面报错的问题啦,如果以后遇见相关的问题,我会补充进去搭。

评论

暂无评论