index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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, socialLogin } from '@/api/auth'
  6. const TokenKey = 'App-Token'
  7. Vue.use(Vuex) // vue的插件机制
  8. // Vuex.Store 构造器选项
  9. const store = new Vuex.Store({
  10. state: {
  11. openExamine: false, // 是否开启审核状态。用于小程序、App 等审核时,关闭部分功能。TODO 芋艿:暂时没找到刷新的地方
  12. token: uni.getStorageSync(TokenKey), // 用户身份 Token
  13. userInfo: {}, // 用户基本信息
  14. timerIdent: false // 全局 1s 定时器,只在全局开启一个,所有需要定时执行的任务监听该值即可,无需额外开启 TODO 芋艿:需要看看
  15. },
  16. getters: {
  17. token: state => state.token,
  18. userInfo: state => state.userInfo,
  19. hasLogin: state => !!state.token
  20. },
  21. mutations: {
  22. // 更新 state 的通用方法
  23. SET_STATE_ATTR(state, param) {
  24. if (param instanceof Array) {
  25. for (let item of param) {
  26. state[item.key] = item.val
  27. }
  28. } else {
  29. state[param.key] = param.val
  30. }
  31. },
  32. // 更新token
  33. SET_TOKEN(state, data) {
  34. // 设置 Token
  35. const { token } = data
  36. state.token = token
  37. uni.setStorageSync(TokenKey, token)
  38. // 加载用户信息
  39. this.dispatch('ObtainUserInfo')
  40. },
  41. // 更新用户信息
  42. SET_USER_INFO(state, data) {
  43. state.userInfo = data
  44. },
  45. // 清空 Token 和 用户信息
  46. CLEAR_LOGIN_INFO(state) {
  47. uni.removeStorageSync(TokenKey)
  48. state.token = ''
  49. state.userInfo = {}
  50. }
  51. },
  52. actions: {
  53. //账号登录
  54. Login({ state, commit }, { type, data }) {
  55. if (type === 0) {
  56. return passwordLogin(data).then(res => {
  57. commit('SET_TOKEN', res.data)
  58. })
  59. } else if (type === 1) {
  60. return smsLogin(data).then(res => {
  61. commit('SET_TOKEN', res.data)
  62. })
  63. } else {
  64. return socialLogin(data).then(res => {
  65. commit('SET_TOKEN', res.data)
  66. })
  67. }
  68. },
  69. // 退出登录
  70. async Logout({ state, commit }) {
  71. commit('CLEAR_LOGIN_INFO')
  72. await logout()
  73. },
  74. // 获得用户基本信息
  75. async ObtainUserInfo({ state, commit }) {
  76. const res = await getUserInfo()
  77. commit('SET_USER_INFO', res.data)
  78. }
  79. }
  80. })
  81. export default store