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

2,543 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情

问题:

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

报错如下图所示: 在这里插入图片描述

原因: 这个错误是 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);
};

相应文件及位置:

在这里插入图片描述

拓展

Vue Router中 router.push、router.replace、router.go 的区别

router.push(location) 相当于 window.history.pushState
想要导航到不同的 URL,则使用 router.push 方法。
这个方法会向 history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。

router.replace(location) 相当于 window.history.replaceState
跟 router.push 很像,区别:它不会向 history 添加新记录,而是替换掉当前的 history 记录,点击返回会跳转到上上个页面。

router.go(n) 相当于 window.history.go
向前或者向后跳转n个页面,n可为正整数或负整数。可以通过 window.history.length 得到历史记录栈中一共有多少页。

Vue Router 的导航方法 (push、 replace、 go) 在各类路由模式 (history、 hash 和 abstract) 下表现一致。

传送门:Vue Router 中实现在新窗口打开页面