import { login, logout, getInfo } from '@/api/login'; import { getToken, setToken, removeToken } from '@/utils/auth'; import defAva from '@/assets/images/login/user.png'; import Cookies from 'js-cookie'; const useUserStore = defineStore('user', { state: () => ({ token: getToken(), name: '', avatar: '', roles: [], userInfo: {}, permissions: [], userId: "", chartColor: ['#8BD1F5', '#26ACFE', '#FAB599', '#FB734D', '#8BD1F5', '#4085FF', '#FAB599'], //echarts颜色全局设置 }), actions: { // 登录 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; 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; this.userId = data.user.userId; 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;