user.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // 上次启动时的用户信息
  2. let userInfoHistory = uni.getStorageSync('userInfo') || {};
  3. let state = {
  4. //是否已经登录
  5. hasLogin: Boolean(Object.keys(userInfoHistory).length),
  6. //用户信息
  7. info: userInfoHistory
  8. },
  9. getters = {
  10. info(state) {
  11. return state.info;
  12. },
  13. hasLogin(state){
  14. return state.hasLogin;
  15. }
  16. },
  17. mutations = {
  18. login(state, info) { //登录成功后的操作
  19. //原有的结合传来的参数
  20. let _info = state.info;
  21. state.info = Object.assign({}, _info, info);
  22. //设置为已经登录
  23. state.hasLogin = true;
  24. console.log('用户信息、',state.info);
  25. //存储最新的用户数据到本地持久化存储
  26. uni.setStorageSync('userInfo', state.info);
  27. if(info.token){
  28. uni.setStorage({
  29. key: 'uni_id_token',
  30. data: state.info.token,
  31. complete(e){
  32. // console.log('setStorage-------',e);
  33. }
  34. });
  35. uni.setStorageSync('uni_id_token_expired', state.info.tokenExpired)
  36. }
  37. },
  38. logout(state) {
  39. state.info = {};
  40. state.hasLogin = false;
  41. uni.setStorageSync('userInfo', {});
  42. uni.removeStorageSync('uni_id_token');
  43. uni.setStorageSync('uni_id_token_expired', 0)
  44. }
  45. },
  46. actions = {
  47. logout(context){
  48. uni.showLoading({mask:true})
  49. uniCloud.callFunction({
  50. name:'uni-id-cf',
  51. data:{action:'logout'},
  52. complete: (e) => {
  53. console.log(e);
  54. context.commit('logout')
  55. uni.hideLoading()
  56. }
  57. })
  58. }
  59. }
  60. export default {
  61. namespaced: true,
  62. state,
  63. getters,
  64. mutations,
  65. actions
  66. }