vue-router beforeEach跳转路由验证用户登录状态

88487804 2018-12-26

使用vue判断验证用户登录状态

  • 导航钩子类似于生命周期钩子,包含路由进入前,进入后,更新时,退出前等几个周期,主要用于控制导航的前进后退或跳转等。
  • 其中router.beforeEach就是路由进入前的周期,同时有路由的来源和去向两个参数,可以判断和控制当前路由的走向和重定向。
  • 一般router.beforeEach配合vuex全局状态储存使用,验证用户登录状态。也可以结合sessionStorage 和localStorage使用,原理相同。

用户登录状态验证

路由配置

定义需要判断登录状态的meta 属性auth

const routes =[
  {
    path:'/',
    component: resolve => require(['../components/mainTem/Filtrate.vue'],resolve),
    meta:{auth:true,keepAlive: false},
    name:'Filtrate'
  },//首页
  {
    path:'/Home',
    component: resolve => require(['../components/mainTem/Home.vue'],resolve),
    meta:{auth:true,keepAlive: true },
    name:'Home'
  },//登录
  {
    path:'/Login',
    component: resolve => require(['../components/mainTem/Login.vue'],resolve),
    meta:{auth:true,keepAlive: false},
    name:'Login'
  },//最新案例
  {
    path:'/NewCase',
    component: resolve => require(['../components/mainTem/NewCase.vue'],resolve),
    meta:{auth:true,keepAlive: true},
    name:'NewCase'
  },//推荐
  {
    path:'/Recommend',
    component: resolve => require(['../components/mainTem/Recommend.vue'],resolve),
    meta:{auth:true,keepAlive: true},
    name:'Recommend'
  },//个人中心
  {
    path:'/User',
    component: resolve => require(['../components/mainTem/User.vue'],resolve),
    meta:{auth:true,keepAlive: true},
    name:'User'
  },//筛选
  {
    path:'/Filtrate',
    component: resolve => require(['../components/mainTem/Filtrate.vue'],resolve),
    meta:{auth:true,keepAlive: false},
    name:'Filtrate'
  },
  {//详情
    path:'/Detail',
    component: resolve => require(['../components/mainTem/Detail.vue'],resolve),
    meta:{auth:true,keepAlive: false},
    name:'Detail'
  }
]

监听

我用的是localStorage储存的用户token值。

业务逻辑:用户没有localStorage说明是第一次登录,则直接跳到登录页面,在登录页面储存token值,存在localStorage,用户关闭页面后,在24小时内,再次打开页面直接进入主页面,通过localStorage去判断当前token是否有效,如果已失效,则提示登录已超时,重新跳到登录页面。

meta
只有在路由中设置了meta auto属性为true的才判断,以上路由全部由设置

to
to为向后走的路由对象,包括路由的完整信息

from
from为从哪跳来的路由对象

next()
next()控制路由向下走,重新定义路由跳转的路由next(‘路由路径)

/** 验证用户是否登录 **/
router.beforeEach((to,from,next) => {
  if(to.matched.some( m => m.meta.auth)) {
    // console.log("先判断是否登录");
    if(to.name=='Login'){
      next();
    }else{
     if(localStorage.getItem('token')){

     //访问服务器缓存数据,判断当前token是否失效
      Vue.http.get("http:xxxx/Login/UserIsLogin?token="+localStorage.getItem('token')+"&url="+to.name,{withCredentials: true}).then(response => response.json()).then(num => {
          // console.log('是否登录',num);
          if(num.code==1001){
            next();
          }else{
            alert('您的token已超时,请重新登录');
            next('/Login');
          }
      })
     }else{
      next('/Login');
     }

    }
  } else {
    console.log("请先登录");
    next()
  }
})

相关推荐