Newer
Older
urbanLifeline_YanAn / src / store / modules / user.js
@zhangqy zhangqy on 17 Oct 2 KB 修改交互逻辑
  1. import { login, logout, getInfo } from "@/api/login";
  2. import { getToken, setToken, removeToken } from "@/utils/auth";
  3. import defAva from "@/assets/images/profile.jpg";
  4. import Cookies from "js-cookie";
  5. const useUserStore = defineStore("user", {
  6. state: () => ({
  7. token: getToken(),
  8. name: "",
  9. avatar: "",
  10. roles: [],
  11. userInfo: {},
  12. permissions: [],
  13. ZhuanTiType: 1
  14. }),
  15. actions: {
  16. // 登录
  17. login(userInfo) {
  18. const username = userInfo.username.trim();
  19. const password = userInfo.password;
  20. const code = userInfo.code;
  21. const uuid = userInfo.uuid;
  22. return new Promise((resolve, reject) => {
  23. login(username, password, code, uuid)
  24. .then((res) => {
  25. let data = res.data;
  26. setToken(data.access_token);
  27. this.token = data.access_token;
  28. resolve();
  29. })
  30. .catch((error) => {
  31. reject(error);
  32. });
  33. });
  34. },
  35. // 获取用户信息
  36. getInfo() {
  37. return new Promise((resolve, reject) => {
  38. getInfo()
  39. .then((res) => {
  40. const data = res.data;
  41. data.user.posts = data.posts;
  42. this.userInfo = data.user;
  43. const avatar =
  44. data.user.avatar == "" || data.user.avatar == null
  45. ? defAva
  46. : data.user.avatar;
  47.  
  48. if (data.roleIds && data.roleIds.length > 0) {
  49. // 验证返回的roles是否是一个非空数组
  50. this.roles = data.roleIds;
  51. this.permissions = data.permissions;
  52. } else {
  53. this.roles = ["ROLE_DEFAULT"];
  54. }
  55. this.name = data.user.userName;
  56. this.avatar = avatar;
  57. resolve(res);
  58. })
  59. .catch((error) => {
  60. reject(error);
  61. });
  62. });
  63. },
  64. // 退出系统
  65. logOut() {
  66. return new Promise((resolve, reject) => {
  67. logout(this.token)
  68. .then(() => {
  69. this.token = "";
  70. this.roles = [];
  71. Cookies.remove("showFlag");
  72. this.permissions = [];
  73. removeToken();
  74. resolve();
  75. })
  76. .catch((error) => {
  77. reject(error);
  78. });
  79. });
  80. },
  81. },
  82. });
  83.  
  84. export default useUserStore;