vue 常用路由守卫

全局前置守卫

  • to:router即将进入的路由对象
  • from:当前导航即将离开的路由
  • next:Function,进行管道中的一个钩子,如果执行完了,则导航的状态就是 confirmed (确认的);否则为false,终止导航。
router.beforeEach((to,from,next)=>{
  let token = getCookie("token");
  console.log(token.length);
  if(to.path == '/' || to.path == '/bilityform' || to.path == '/login' || token.length>0){
    next();
  }
  else{
    alert('您还没有登录,请先登录');
    next('/');
  }
})

全局后置守卫:

 router.afterEach((to, from) => {
    console.log('全局后置守卫')
  })

组件内路由:

到达组件前:

//进入该路由时判断如果有token 如果没有token,转到登录页面

     beforeRouteEnter:(to,from,next)=>{
          var tokens=getCookie("token");
           if(tokens.length>0){
               next()
           }else{
               alert("请您先登录")
               next('/login')
           }
          
    },

离开组件时:

beforeRouteLeave:(to,from,next)=>{
        if(confirm("确定离开此页面吗?") == true){
            next();
        }else{
            next(false);
        }
    

 

你可能感兴趣的:(Vue,案例,Vue小笔记)