user.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import {
  2. getInfo,
  3. login,
  4. loginPhone,
  5. logout
  6. } from '@/api/user'
  7. import {
  8. getToken,
  9. removeToken,
  10. setToken
  11. } from '@/utils/auth'
  12. import {
  13. EventBus,
  14. Events
  15. } from '@/utils/event-bus'
  16. import store from '@/store'
  17. const user = {
  18. state: {
  19. token: getToken(),
  20. user: null
  21. },
  22. mutations: {
  23. SET_TOKEN: (state, token) => {
  24. state.token = token
  25. uni.setStorageSync('token', token)
  26. setToken(token)
  27. },
  28. SET_USER: (state, user) => {
  29. state.user = user
  30. uni.setStorageSync('user', user)
  31. EventBus.$emit(Events.USER_INFO_UPDATE, {
  32. 'user': user
  33. })
  34. },
  35. SET_PHONE: (state, phone) => {
  36. state.phone = phone
  37. }
  38. },
  39. actions: {
  40. // 短信登录
  41. loginPhone({
  42. commit,
  43. dispatch
  44. }, userInfo) {
  45. return new Promise((resolve, reject) => {
  46. loginPhone(userInfo).then(response => {
  47. const data = response.data
  48. commit('SET_TOKEN', data.token)
  49. commit('SHOW_LOADING')
  50. dispatch('getInfo')
  51. resolve()
  52. }).catch(error => {
  53. reject(error)
  54. })
  55. })
  56. },
  57. // 登录
  58. login({
  59. commit,
  60. dispatch,
  61. state
  62. }, userInfo) {
  63. userInfo.username = userInfo.username.trim()
  64. return new Promise((resolve, reject) => {
  65. login(userInfo).then(response => {
  66. const data = response.data
  67. commit('SET_TOKEN', data.token)
  68. commit('SHOW_LOADING')
  69. dispatch('getInfo')
  70. resolve()
  71. }).catch(error => {
  72. reject(error)
  73. })
  74. })
  75. },
  76. // 获取用户信息
  77. getInfo({
  78. commit,
  79. state
  80. }, params) {
  81. return new Promise((resolve, reject) => {
  82. params = params || {}
  83. getInfo(params).then(response => {
  84. const data = response.data
  85. commit('SET_USER', data)
  86. store.commit('HIDE_LOADING')
  87. resolve(response)
  88. }).catch(error => {
  89. reject(error)
  90. store.commit('HIDE_LOADING')
  91. })
  92. })
  93. },
  94. // 登出
  95. logout({
  96. commit,
  97. dispatch,
  98. state
  99. }) {
  100. return new Promise((resolve, reject) => {
  101. logout().then(() => {
  102. resolve()
  103. dispatch('fedLogOut')
  104. }).catch(error => {
  105. reject(error)
  106. dispatch('fedLogOut')
  107. })
  108. })
  109. },
  110. // 前端 登出
  111. fedLogOut({
  112. commit
  113. }) {
  114. return new Promise(resolve => {
  115. removeToken()
  116. commit('SET_TOKEN', '')
  117. commit('SET_USER', null)
  118. resolve()
  119. })
  120. }
  121. }
  122. }
  123. export default user