vue路由导航守卫

1. router.beforeEach((to,from,next)=>{})

2. 回调函数中的参数,to: 目标路由

from: 当前路由
next() 跳转 一定要调用
next(false);//禁止跳转
next(true);//允许跳转
next(’/login’)//跳转路径
next({path:’/login’,params:{},query:{}})//携带参数

//前置
router.beforeEach((to,from,next)=>{
//如果要去My或者index页面
  if(to.path=='/My' || to.path=='/index' ){
  //判断l如果ocalStorage里面是否有Username
    if(localStorage.getItem("username")){
   //有用户信息让它继续走
      next(true);
    }else{
      //否则让它跳转到登录界面,跳转到登录界面时,需要把to.path传入,方便在登录成功时跳转到对应界面上
      next({"path":"/Login",query:{"topath":to.path}})
    }
  }else{
  //否则去其他界面时 让它继续走
    next(true);
  }
})
posted @ 2021-07-05 13:02  YokeF  阅读(114)  评论(0)    收藏  举报