import { login, logout, getInfo } from '@/api/login'; import { getToken, setToken, removeToken } from '@/utils/auth'; import defAva from '@/assets/images/profile.jpg'; import Cookies from 'js-cookie'; const useUserStore = defineStore('user', { state: () => ({ token: getToken(), name: '', avatar: '', roles: [], userInfo: {}, permissions: [], MapData: [], MapDataCount: [], }), actions: { SET_MapData(MapData) { this.MapData = MapData; }, SET_MapData_COUNT(count){ this.MapDataCount = count; }, // 登录 login(userInfo) { const username = userInfo.username.trim(); const password = userInfo.password; const code = userInfo.code; const uuid = userInfo.uuid; return new Promise((resolve, reject) => { login(username, password, code, uuid) .then(res => { let data = res.data; setToken(data.access_token); this.token = data.access_token; resolve(); }) .catch(error => { reject(error); }); }); }, // 获取用户信息 getInfo() { return new Promise((resolve, reject) => { getInfo() .then(res => { const data = res.data; data.user.posts = data.posts; console.log('data.user', data.user); this.userInfo = data.user; const avatar = data.user.avatar == '' || data.user.avatar == null ? defAva : data.user.avatar; if (data.roleIds && data.roleIds.length > 0) { // 验证返回的roles是否是一个非空数组 this.roles = data.roleIds; this.permissions = data.permissions; } else { this.roles = ['ROLE_DEFAULT']; } this.name = data.user.userName; this.avatar = avatar; resolve(res); }) .catch(error => { reject(error); }); }); }, // 退出系统 logOut() { return new Promise((resolve, reject) => { logout(this.token) .then(() => { this.token = ''; this.roles = []; Cookies.remove('showFlag'); this.permissions = []; removeToken(); resolve(); }) .catch(error => { reject(error); }); }); }, }, }); export default useUserStore;