Redirected when going from “/login“ to “/“ via a navigation guard错误

808 阅读1分钟

本文已参与「新人创作礼」活动, 一起开启掘金创作之路。 ​

 路由版本:"vue-router": "^3.5.2",

添加了路由守卫,然后开始报这个错误,

原因就是路由版本导致的

解决办法

// 导航守卫限制路由跳转
router.beforeEach((to, from, next) => { 
	if (to.path === '/login') {
		next()
		var tokenStr = window.sessionStorage.getItem('token')
	}
	if (!tokenStr) {
		next()
	} else {
		next('/login')
	}
})
// router  要跟你引用的路由名称一致

路由版本3.2到3.0的话,应该可以用下面这个办法解决

1. 

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 导航守卫限制路由跳转
router.beforeEach((to, from, next) => {
	if (!to.meta.isPublic && !localStorage.token){
		return next('/login')
	}
	next()
})