user.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { ACCESS_TOKEN } from '@/store/mutation-types'
  2. import storage from '@/utils/storage'
  3. import * as LoginApi from '@/api/login'
  4. import * as UserApi from '@/api/user'
  5. // 登陆成功后执行
  6. const loginSuccess = (commit, { token }) => {
  7. // 过期时间30天
  8. const expiryTime = 30 * 86400
  9. // 保存tokne和userId到缓存
  10. storage.set(ACCESS_TOKEN, token, expiryTime)
  11. // 记录到store全局变量
  12. commit('SET_TOKEN', token)
  13. }
  14. export const state = {
  15. // 用户认证token
  16. token: '',
  17. // 用户信息
  18. userInfo: null
  19. }
  20. export const mutations = {
  21. SET_TOKEN: (state, value) => {
  22. state.token = value
  23. },
  24. SET_USER: (state, value) => {
  25. state.userInfo = value
  26. },
  27. }
  28. export const actions = {
  29. // 用户登录(普通登录: 输入账号、密码和验证码)
  30. Login({ commit }, data) {
  31. return new Promise((resolve, reject) => {
  32. LoginApi.login(data, { custom: { catch: true } }).then(response => {
  33. const result = response;
  34. loginSuccess(commit, result)
  35. resolve(response)
  36. }).catch(reject)
  37. })
  38. },
  39. // 用户信息
  40. Info({ commit, state }) {
  41. return new Promise((resolve, reject) => {
  42. if (state.userInfo) {
  43. return resolve(state.userInfo)
  44. }
  45. UserApi.getInfo().then(response => {
  46. const result = response;
  47. commit('SET_USER', result)
  48. resolve(response)
  49. }).catch(reject)
  50. })
  51. },
  52. // 退出登录
  53. Logout({ commit }, data) {
  54. return new Promise((resolve, reject) => {
  55. LoginApi.logout(data, { custom: { catch: true } }).then(response => {
  56. storage.remove(ACCESS_TOKEN)
  57. commit('SET_TOKEN', '')
  58. resolve(response)
  59. }).catch(reject)
  60. })
  61. }
  62. }