user.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import { userService } from '@/services/index.js'
  2. import authorize from '@/common/authorize.js'
  3. import { msg as showMsg } from '@/common/util.js'
  4. import { switchTabTo } from '@/common/utilsTools.js'
  5. const state = {
  6. userId: '',
  7. userIdentity: '',
  8. userInfo: null,
  9. hasLogin: false,
  10. isWxAuthorize: false,
  11. }
  12. const mutations = {
  13. // 用户登录
  14. LOGIN(state, data) {
  15. const userInfo = JSON.parse(data)
  16. state.userInfo = userInfo
  17. state.hasLogin = true
  18. state.isWxAuthorize = true
  19. state.userId = userInfo.userId
  20. state.userIdentity = userInfo.userIdentity
  21. uni.setStorageSync('openId', userInfo.openId)
  22. },
  23. // 退出登录
  24. LOGIN_OUT(state, data) {
  25. const userInfo = JSON.parse(data) || null
  26. state.userInfo = userInfo
  27. state.hasLogin = false
  28. state.isWxAuthorize = false
  29. state.userId = ''
  30. state.userIdentity = ''
  31. userInfo && uni.setStorageSync('openId', userInfo.openId)
  32. },
  33. }
  34. const actions = {
  35. // 微信授权登录
  36. async wechatlogin({ commit, dispatch, state }) {
  37. // 获取code
  38. const code = await authorize.getCode('weixin')
  39. userService.UserWechatAuthorLogin({ code })
  40. .then(response => {
  41. commit('LOGIN', response.data)
  42. dispatch('cart/getCartNumber', state.userId, { root: true })
  43. })
  44. .catch(error => {
  45. commit('LOGIN_OUT', response.data)
  46. })
  47. },
  48. // 手机号注册登录
  49. async customLogin({ commit }, params) {
  50. userService.UserMobileLogin(params)
  51. .then(response => {
  52. // 保存用户信息
  53. commit('LOGIN', response.data)
  54. // 登录成功提示
  55. showMsg('登录成功', 1500, false, 'success')
  56. setTimeout(() => {
  57. switchTabTo('/pages/tabBar/index/index')
  58. }, 1500)
  59. })
  60. .catch(error => {
  61. showMsg(error.msg, 2000)
  62. })
  63. }
  64. }
  65. export default {
  66. namespaced: true,
  67. state,
  68. mutations,
  69. actions
  70. }