VUE登录点击两次才能跳转Navigation cancelled from “/login“ to “/index“ with a new navigation.

使用vue开发项目时在登录界面遇到vue-router报错
Uncaught (in promise) Error: Navigation cancelled from "/login" to "/index" with a new navigation.

解决报错的问题

// 在自己项目router里边
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) {
    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)
}

也可使用catch捕获错误,防止报错

 this.$router.push({ name: "Home" }).catch((err) => {})

解决点击两次问题

这个时候不会报错了,但是点击登录按钮的时候发现需要点击两次才可以登录主页面,解决办法参考自以下博主文章
1、在调用push的时候,设置回调函数

 this.$router.push({ name: "Home" }, (onComplete) => {},(onAbort) => {});

主要参考:设置回调函数方法
2、在导航守卫时

beforeEach((to, from, next) => {
	// 想要进入页面必须判断有无登录,
	if(to.path !== '/login') {
		if(...){
			//表示已经登录过了,可以直接进入想要的页面
			next();// 就在这儿出现了问题
		}else{
			// 没有登录则进入login界面
			next('/login');
		}
	}
}

在进行next()的时候没有进行传参,在你点击一次之后他不知道往哪个路由走,只有再次点击的是偶才知道你this.$router.push()的路径
next 传参的话相当于要再一次调用路由守卫

beforeEach((to, from, next) => {
	// 想要进入页面必须判断有无登录,
	if(to.path !== '/login') {
		if(...){
			//表示已经登录过了,可以直接进入想要的页面
			next( { ...to} );
		}else{
			// 没有登录则进入login界面
			next('/login');
		}
	}
}

主要参考:导航守卫解决

  • 4
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值