vue-router 报错:Navigation cancelled from “/…“ to “/…“ with a new navigation

目录
文章目录隐藏
  1. 问题
  2. 解决方法

问题

项目中需要对用户是否登录进行判断,如果用户未登录或者 token 过期就需要跳转登录页面,进行登录验证。所以需要做一个拦截,在跳转登录页面时报了一个错。

报错如下图所示:

vue-router 报错:Navigation cancelled from “/...“ to “/...“ with a new navigation

原因:

这个错误是 vue-router 内部错误,没有进行 catch 处理,导致的编程式导航跳转问题,向同一地址跳转时会报错的情况(push 和 replace 都会导致这个情况的发生)。

解决方法

方案一:

安装 vue-router 3.0 以下版本,先卸载 3.0 以上版本然后再安装旧版本 。

npm install vue-router@2.8.0 -S

方案二:

针对于路由跳转相同的地址添加 catch 捕获一下异常。

this.$router.push({path:'/register'}).catch(err => { console.log(err) })

方案三:

在路由 router 里面加上以下这段代码:

// 解决编程式路由往同一地址跳转时会报错的情况
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);
};

相应文件及位置:

相应文件及位置

「点点赞赏,手留余香」

0

给作者打赏,鼓励TA抓紧创作!

微信微信 支付宝支付宝

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
码云笔记 » vue-router 报错:Navigation cancelled from “/…“ to “/…“ with a new navigation

发表回复