user.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { login, logout, getInfo } from '@/api/login'
  2. import auth from '@/utils/auth'
  3. import Vue from 'vue'
  4. import cacheMixin from '@/components/Cache/mx-cache-mixin'
  5. const user = {
  6. state: auth.getUserInfo(),
  7. mutations: {
  8. RELOAD: (state, newInfo) => {
  9. console.log('RELOAD this', state, newInfo)
  10. Object.keys(newInfo).forEach(key => {
  11. if (!state.hasOwnProperty(key)) {
  12. // NOTE:使用Vue.set动态添加监控属性
  13. Vue.set(state, key, newInfo[key])
  14. }
  15. state[key] = newInfo[key]
  16. })
  17. }
  18. },
  19. actions: {
  20. // 登录
  21. Login({ commit }, userInfo) {
  22. const username = userInfo.username.trim()
  23. const password = userInfo.password
  24. return new Promise((resolve, reject) => {
  25. login(username, password).then(res => {
  26. auth.setToken(res.token)
  27. resolve()
  28. }).catch(error => {
  29. reject(error)
  30. })
  31. })
  32. },
  33. // 获取用户信息
  34. GetInfo({ commit, state }) {
  35. return new Promise((resolve, reject) => {
  36. getInfo().then(res => {
  37. console.log('xxxxxxxxxxx', res);
  38. const user = res.data
  39. user.avatar == user.avatar || require("@/assets/images/profile.jpg")
  40. commit('RELOAD', user)
  41. auth.setUserInfo(user)
  42. cacheMixin.methods.clearUserCache() // NOTE:纯作为静态方法在调用,有更优雅的方式?
  43. resolve(res)
  44. }).catch(error => {
  45. reject(error)
  46. })
  47. })
  48. },
  49. // 退出系统
  50. LogOut({ commit, state }) {
  51. return new Promise((resolve, reject) => {
  52. logout(state.token).then(() => {
  53. auth.removeToken()
  54. resolve()
  55. }).catch(error => {
  56. reject(error)
  57. })
  58. })
  59. }
  60. }
  61. }
  62. export default user