路由守卫

99 阅读1分钟

路由全局前置守卫

router.beforeEach((to,from,next)=>{
    // to将要去的路径  from从哪来上个路由 next中间件的意思(好像是钩子函数)
const isLogined = localStorage.getItem('token')||"";//判断有没有登录
})
   //表示没有登录
if(!isLogined){
 //没有登录的情况下分为两种情况,一个是在登录页 ,一个是在其他页面
    if(to.path=="/login"){
        next();//直接显示登录页面
    }else{
        //其他页面
        next("/login")
    }
}else{
    //表示已经登录
     if(to.path=="/login"){
        next("/");//如果已经登录,你在登录页面,那么要跳转到首页
    }else{
        next();//否则其他页面放行
    }
}
    
})

路由全局后置守卫

//走了打拜拜用的
router.afterEach((to,from,next)=>{})

路由独享守卫

//配置到路由身上
//在路由里面配置
beforenter:(to,from,next)=>{
    var login = localStorage.getitem("token")||"";
    if(!isLogind){
        next('/login');
       }else{
         next()
		}
})

路由组件内守卫

  //组件内守卫
  beforeRouteEnter(to, from, next) {
      const isLogind = localStorage.getItem("token")||"";
      if(!isLogind){
          next('/login');
      }else{
          next();
      }
  },