vue 项目中处理用户登录验证以及会员等级的更新的记录

最近用vue撸一个微信公众号的项目,项目需要用户登录,不登录是不开放页面的,所以在main.js中用到了全局的路由守卫

//main.js,用户信息分别保存在本地localStorage和store中,作为长久保存,只需一次登录
router.beforeEach(function (to, from, next) {
  if(!localStorage.getItem('userInfo') && to.path!='/authorization'){
    //首次登录,或者本地个人信息清除了
    console.log('登录授权');
    router.push({path:'/authorization'})
  }else if(localStorage.getItem('userInfo') && !store.state.userInfo){
    //已经登录授权,需要更新获取用户信息
    console.log('重新获取用户信息');
    store.dispatch('userInfo');
  }else{
    console.log('已经登录,也不需要获取用户信息');
  }
/* 路由发生变化修改页面title */
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next();  
})

这样的话,用户只需要登录一次就可以了,当用户的身份改变的时候,只需要删除store中用户的信息,然后在actions中去重新获取用户的身份,并且更新本地localStorage中用户的身份

userInfo:function(context){
   var userInfo= JSON.parse(localStorage.getItem('userInfo')) || {};
   getName({
      username: userInfo.phone,
      access_token: userInfo.access_token,
      shop_type: 6,
      openid:userInfo.openid
   }).then(res=>{
      console.log(res);
      if(res.data.status=='y'){
         var group_id=res.data.result.group_id;
         var username=res.data.result.username;
         userInfo.member_group=group_id;
         userInfo.phone=username;
         context.commit('userInfo',userInfo); 
         localStorage.setItem('userInfo',JSON.stringify(userInfo));
       }
    })  
}

不知道这样子处理好不好,上面的路由守卫验证登录也是在网上看了好多帖子,由于有一段时间了,地址也没找到,在这里做一个记录

猜你喜欢

转载自blog.csdn.net/qq_41620704/article/details/84316490