需求:
登陆之后才能查看主页面,否则跳转至登录页
遇到的问题:
刚刚在做Vue项目时出现了这个错误,错误原因就是我们由于在路由之间进行了多次导航,可能是因为您的代码中有一些逻辑错误或重复代码。
一开始是打算直接在拦截器跳转路由的,发现会报错Avoided redundant navigation to current location: "/login".
1.解决这个问题:
将这段代码加入到router文件夹下的index.js文件里面
// 针对ElementUI导航栏中重复导航报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
return originalPush.call(this, location).catch(err => err)
}
2.可以用全局路由守卫来解决:
将这段代码加入到router文件夹下的index.js文件里面,添加全局路由守卫,并通过cookies存储信息
router.beforeEach((to,from,next)=>{
const admin = Cookies.get('admin')
if(!admin){
if(to.path!=='/login'){
next({path:"/login"})
}else{
next()
}
}else{
next()
}
})