(编辑:jimmy 日期: 2024/11/19 浏览:2)
使用vue判断验证用户登录状态
用户登录状态验证
路由配置
定义需要判断登录状态的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"+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() } })
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。