user.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { ACCESS_TOKEN, USER_ID } from '@/store/mutation-types'
  2. import storage from '@/utils/storage'
  3. import * as LoginApi from '@/api/login'
  4. // 登陆成功后执行
  5. const loginSuccess = (commit, { token, userId }) => {
  6. // 过期时间30天
  7. const expiryTime = 30 * 86400
  8. // 保存tokne和userId到缓存
  9. storage.set(USER_ID, userId, expiryTime)
  10. storage.set(ACCESS_TOKEN, token, expiryTime)
  11. // 记录到store全局变量
  12. commit('SET_TOKEN', token)
  13. commit('SET_USER_ID', userId)
  14. }
  15. const user = {
  16. state: {
  17. // 用户认证token
  18. token: '',
  19. // 用户ID
  20. userId: null,
  21. // 用户信息
  22. userInfo: storage.get('wx_userinfo') || null,
  23. },
  24. mutations: {
  25. SET_TOKEN: (state, value) => {
  26. state.token = value
  27. },
  28. SET_USER_ID: (state, value) => {
  29. state.userId = value
  30. }
  31. },
  32. actions: {
  33. // 用户登录 (普通登录: 输入手机号和验证码)
  34. Login({ commit }, data) {
  35. return new Promise((resolve, reject) => {
  36. LoginApi.login({ form: data })
  37. .then(response => {
  38. const result = response.data
  39. loginSuccess(commit, result)
  40. resolve(response)
  41. })
  42. .catch(reject)
  43. })
  44. },
  45. // 微信小程序一键授权登录 (获取用户基本信息)
  46. LoginMpWx({ commit }, data) {
  47. return new Promise((resolve, reject) => {
  48. LoginApi.loginMpWx({ form: data }, { isPrompt: false })
  49. .then(response => {
  50. const result = response.data
  51. loginSuccess(commit, result)
  52. resolve(response)
  53. })
  54. .catch(reject)
  55. })
  56. },
  57. // 微信小程序一键授权登录 (授权手机号)
  58. LoginMpWxMobile({ commit }, data) {
  59. return new Promise((resolve, reject) => {
  60. LoginApi.loginMpWxMobile({ form: data }, { isPrompt: false })
  61. .then(response => {
  62. const result = response.data
  63. loginSuccess(commit, result)
  64. resolve(response)
  65. })
  66. .catch(reject)
  67. })
  68. },
  69. // 退出登录
  70. Logout({ commit }, data) {
  71. const store = this
  72. return new Promise((resolve, reject) => {
  73. if (store.getters.userId > 0) {
  74. // 删除缓存中的tokne和userId
  75. storage.remove(USER_ID)
  76. storage.remove(ACCESS_TOKEN)
  77. // 记录到store全局变量
  78. commit('SET_TOKEN', '')
  79. commit('SET_USER_ID', null)
  80. resolve()
  81. }
  82. })
  83. }
  84. }
  85. }
  86. export default user