vue-router 跳转异常 Error: Navigation cancelled from “/“ to “/home“ with a new navigation.

异常信息:Error: Havigation cancelled from"/" to "/home" with a new navigation ,如下图:

原因:

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

        2、vue-router@3.0版本及以上回调形式已经改成promise api的形式了,返回的是一个promise,如果路由地址跳转相同, 且没有捕获到错误,控制台始终会出现如图所示的警告 (注:3.0以下版本则不会出现以下警告!!!,因路由回调问题…) 

解决:

方案一:

        安装vue-router3.0以下版本:先卸载3.0以上版本然后再安装旧版本 npm install vue-router@2.8.0 -S

方案二:

        针对于路由跳转相同的地址添加catch捕获一下异常:this.$router.push(‘/location’).catch(err => { console.log(err) })

方案三:

        在main.js下注册一个全局函数即可 (注:此处理方案只针对于vue-router 3.0以上版本哈!!!)

import Router from 'vue-router'

const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

注:官方vue-router@3.0及以上新版本路由默认回调返回的都是promise,原先就版本的路由回调将废弃!!!!

方法四(重写push):

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

方法五 在router的index.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);
};
 

本文使用得是方案一,降低vue-router版本:

原版本为 vue-router 3.2.0,卸载 npm uninstall vue-router 

安装 npm install vue-router@2 

安装完成后,package.json 即可查看依赖: 

再次登录跳转,退出后未发现异常,希望本文对你有帮助。 

  • 16
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值