user.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. console.log('登录成功')
  42. commit('LOGIN', response.data)
  43. dispatch('cart/getCartNumber', state.userId, { root: true }) // 获取购物车数量信息
  44. dispatch('coupon/getCouponActivity', null, { root: true }) // 获取优惠券弹窗信息
  45. })
  46. .catch(error => {
  47. console.log('游客')
  48. dispatch('coupon/getCouponActivity', null, { root: true }) // 游客也要获取优惠券弹窗信息
  49. commit('LOGIN_OUT', error.data)
  50. })
  51. },
  52. // 手机号注册登录
  53. customLogin({ commit, state, dispatch }, params) {
  54. userService.UserMobileLogin(params)
  55. .then(response => {
  56. // 保存用户信息
  57. commit('LOGIN', response.data)
  58. dispatch('cart/getCartNumber', state.userId, { root: true }) // 获取购物车数量信息
  59. dispatch('coupon/getCouponActivity', null, { root: true }) // 获取优惠券弹窗信息
  60. // 登录成功提示
  61. showMsg('登录成功', 1500, false, 'success')
  62. setTimeout(() => {
  63. switchTabTo('/pages/tabBar/index/index')
  64. }, 1500)
  65. })
  66. .catch(error => {
  67. showMsg(error.msg, 2000)
  68. })
  69. }
  70. }
  71. export default {
  72. namespaced: true,
  73. state,
  74. mutations,
  75. actions
  76. }