user.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import ajax from '@/common/ajax'
  2. import store from '@/store'
  3. let state = {
  4. token: uni.getStorageSync('TOKEN'), //是否已经登录
  5. userInfo: uni.getStorageSync('userInfo') || {}, //用户信息
  6. code: uni.getStorageSync('code'), //企微 code
  7. },
  8. getters = {
  9. userInfo(state) {
  10. return state.userInfo;
  11. },
  12. token(state) {
  13. return state.token;
  14. }
  15. },
  16. mutations = {
  17. setUserInfo(state, info) { //登录成功后的操作
  18. //原有的结合传来的参数
  19. state.userInfo = info || {};
  20. state.token = uni.getStorageSync('TOKEN') || '';
  21. uni.setStorageSync('userInfo', info);
  22. },
  23. logout(state) {
  24. state.info = {};
  25. state.token = '';
  26. state.code = '';
  27. uni.setStorageSync('userInfo', {});
  28. uni.removeStorageSync('TOKEN');
  29. uni.setStorageSync('code', '');
  30. },
  31. setToken(state, token) {
  32. state.token = token;
  33. uni.setStorageSync('TOKEN', token);
  34. },
  35. setCode(state, code) {
  36. state.code = code;
  37. uni.setStorageSync('code', code);
  38. },
  39. },
  40. actions = {
  41. login({
  42. commit,
  43. state
  44. },params) {
  45. uni.showLoading({
  46. title: '登录中',
  47. mask: true
  48. })
  49. let token = ''
  50. ajax.post('/shunt/login', {code: state.code, ...params }).then(res => {
  51. token = res?.data?.token || ''
  52. }).catch(error => {
  53. console.error('login', error)
  54. }).finally(() => {
  55. uni.hideLoading()
  56. commit('setToken', token)
  57. if (token) {
  58. store.dispatch('user/updateUserInfo')
  59. uni.reLaunch({
  60. url: '/pages/index/index'
  61. });
  62. } else {
  63. commit('logout', '')
  64. uni.reLaunch({
  65. url: '/pages/error/403/403'
  66. });
  67. }
  68. })
  69. },
  70. updateUserInfo({
  71. commit,
  72. state
  73. }) {
  74. uni.showLoading({
  75. mask: true
  76. })
  77. state.token && ajax.post('/shunt/userinfo').then(res => {
  78. const info = res.data || {}
  79. commit('setUserInfo', info)
  80. }).catch(error => {
  81. console.error('updateUserInfo', error)
  82. commit('setUserInfo', {})
  83. }).finally(() => {
  84. uni.hideLoading()
  85. })
  86. },
  87. }
  88. export default {
  89. namespaced: true,
  90. state,
  91. getters,
  92. mutations,
  93. actions
  94. }