在Vue中通常用 router.beforeEach来做一些路由显示,也就是怎们常说的路由守卫
beforeEach里面有三个参数:to、from、next to: 表示你的目标路由,去哪儿 from: 当前所在的路由 next: 需要用function来调用 必须写的参数
一、现在需要进行路由守卫的路由上面加一个mate参数,如:isRouterAuth:true
这个是表示需要进行路由守卫的路由
path:'/index',
name:"Index",
meta:{isRouterAuth:true},
component: ()=> import('../views/Index.vue')
二、需要用beforeEach进行守卫,(若删除登陆时存储的token,需要重新跳到login重新登陆)
router.beforeEach((to,from,next)=>{
if(to.meta.isRouterAuth){ // 判断当前路由是否需要路由验证
if(getCookie('token')){ // 判断当前的token是否存在
next() // 存在继续执行
}else{
next('/login') //不存在需要跳到登陆页
}
}else{ // 不需要验证路由,继续执行
next()
}
})