亲测解决 :Navigation cancelled from “xxx“ to “xxx“ with a new navigation

41 篇文章 0 订阅

使用vue 3.0 写了一个登入页面,再点击登入的时候,第一次点击会没有反应,F12查看接口都调用了但是没有跳转,控制台打印出错:

错误说有异常没有捕获;

这个错误是vue -router 内部的错误,没有进行catch处理导致的;

再vue-router3.0以上的版本新增功能:push和replace方法会返回一个promise;

解决方案:

在vue的router的js中添加下面代码

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

其中VueRouter是在vue初始化的时候引入的Router,完整代码:router/index.js

import VueRouter from 'vue-router'

Vue.use(VueRouter);
// 解决报错
const originalPush = VueRouter.prototype.push
const originalReplace = VueRouter.prototype.replace
// push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
    console.log(onReject + onResolve)
  // if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => {
      console.log(err)
      originalPush.call(this, location, onResolve, onReject)
  });
}
// replace
VueRouter.prototype.replace = function push (location, onResolve, onReject) {
    console.log(onReject + onResolve)
  // if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => {
      console.log(err)
      originalPush.call(this, location, onResolve, onReject)
  })
}

.......

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值