| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- import { defineStore } from 'pinia'
- import storage from 'store'
- import expirePlugin from 'store/plugins/expire'
- import { login, uniLogin } from '@/api/login'
- import { ChangeUsername, GetUserInfo } from '@/api/user'
- storage.addPlugin(expirePlugin)
- export const useUserStore = defineStore('user', {
- state: () => ({
- session: '',
- uuid: '',
- username: '',
- avatar: '',
- email: '',
- roles: []
- }),
- actions: {
- // 登录
- async login(userInfo) {
- try {
- const res = await login(userInfo)
- if (!res || res.code !== 0) throw new Error(res?.msg || '登录失败!请稍后再试')
- storage.set('user', res.data, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
- this.setUser(res.data)
- return res.data
- } catch (error) {
- throw error
- }
- },
- async uniLogin(type, code) {
- try {
- const res = await uniLogin({type, code})
- if (!res || res.code !== 0) throw new Error(res?.msg || '登录失败!请稍后再试')
- storage.set('user', res.data, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
- this.setUser(res.data)
- return res.data
- } catch (error) {
- throw error
- }
- },
- // 更新用户名
- async changeName(username) {
- try {
- const res = await ChangeUsername({ username })
- if (!res || res.code !== 0) throw new Error(res?.msg || '更新失败!请稍后再试')
- this.username = username
- storage.set('user', this.$state, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
- } catch (error) {
- throw error
- }
- },
- // 获取用户信息
- async getInfo() {
- const user = storage.get('user')
- if (user) {
- this.setUser(user)
- return user
- }
- return this.$state
- },
- async getInfoFromServer() {
- try {
- const res = await GetUserInfo()
- if (!res || res.code !== 0) throw new Error(res?.msg || '获取用户信息失败!请稍后再试')
- storage.set('user', res.data, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
- this.setUser(res.data)
- return res.data
- } catch (error) {
- throw error
- }
- },
- // 登出
- logout() {
- this.setUser({})
- storage.remove('user')
- },
- // 设置用户信息
- setUser(user = {}) {
- this.session = user.session || ''
- this.uuid = user.uuid || ''
- this.avatar = user.avatar || ''
- this.username = user.username || ''
- this.email = user.email || ''
- this.roles = user.roles || []
- }
- }
- })
|