index.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import { logout } from '@/api/auth'
  4. import { getUserInfo } from '@/api/user'
  5. import { passwordLogin, smsLogin, weixinMiniAppLogin } from '@/api/auth'
  6. const AccessTokenKey = 'ACCESS_TOKEN'
  7. const RefreshTokenKey = 'REFRESH_TOKEN'
  8. Vue.use(Vuex) // vue的插件机制
  9. // Vuex.Store 构造器选项
  10. const store = new Vuex.Store({
  11. state: {
  12. accessToken: uni.getStorageSync(AccessTokenKey), // 访问令牌
  13. refreshToken: uni.getStorageSync(RefreshTokenKey), // 刷新令牌
  14. userInfo: {}
  15. },
  16. getters: {
  17. accessToken: state => state.accessToken,
  18. refreshToken: state => state.refreshToken,
  19. userInfo: state => state.userInfo,
  20. hasLogin: state => !!state.accessToken
  21. },
  22. mutations: {
  23. // 更新 state 的通用方法
  24. SET_STATE_ATTR(state, param) {
  25. if (param instanceof Array) {
  26. for (let item of param) {
  27. state[item.key] = item.val
  28. }
  29. } else {
  30. state[param.key] = param.val
  31. }
  32. },
  33. // 更新令牌
  34. SET_TOKEN(state, data) {
  35. // 设置令牌
  36. const { accessToken, refreshToken } = data
  37. state.accessToken = accessToken
  38. state.refreshToken = refreshToken
  39. uni.setStorageSync(AccessTokenKey, accessToken)
  40. uni.setStorageSync(RefreshTokenKey, refreshToken)
  41. // 加载用户信息
  42. this.dispatch('ObtainUserInfo')
  43. },
  44. // 更新用户信息
  45. SET_USER_INFO(state, data) {
  46. state.userInfo = data
  47. },
  48. // 清空令牌 和 用户信息
  49. CLEAR_LOGIN_INFO(state) {
  50. uni.removeStorageSync(AccessTokenKey)
  51. uni.removeStorageSync(RefreshTokenKey)
  52. state.accessToken = ''
  53. state.refreshToken = ''
  54. state.userInfo = {}
  55. }
  56. },
  57. actions: {
  58. //账号登录
  59. Login({ state, commit }, { type, data }) {
  60. if (type === 0) {
  61. return passwordLogin(data).then(res => {
  62. commit('SET_TOKEN', res.data)
  63. })
  64. } else if (type === 1) {
  65. return smsLogin(data).then(res => {
  66. commit('SET_TOKEN', res.data)
  67. })
  68. } else {
  69. return weixinMiniAppLogin(data).then(res => {
  70. commit('SET_TOKEN', res.data)
  71. })
  72. }
  73. },
  74. // 退出登录
  75. async Logout({ state, commit }) {
  76. commit('CLEAR_LOGIN_INFO')
  77. await logout()
  78. },
  79. // 获得用户基本信息
  80. async ObtainUserInfo({ state, commit }) {
  81. const res = await getUserInfo()
  82. commit('SET_USER_INFO', res.data)
  83. }
  84. }
  85. })
  86. export default store