104 lines
2.7 KiB
TypeScript
Raw Normal View History

2025-04-30 01:43:23 +08:00
import {defineStore} from "pinia";
import {authenticationApi, loginCode, loginPass, weChatLogin} from "@/api/system/login";
import {AUTH_KEY} from "@/config";
interface UserState {
userdata: any;
token: string;
auth: string[]
}
export const useUserStore = defineStore({
id: "app-user",
state: (): UserState => ({
//用户数据
userdata: '',
// token
token: '',
//用户注册信息
auth: [],
}),
getters: {
getToken(): string {
return this.token;
},
getUser(): any {
return this.userdata;
},
getAuth(): string[] {
return this.auth;
}
},
actions: {
setToken(token: string) {
this.token = token
},
setUser(data: any) {
this.userdata = data;
},
setAuth(data: string[]) {
this.auth = data;
},
/**
* @description:
*/
async codeLogin(params: { phone: number | string, code: number | string }) {
try {
const {result} = await loginCode({phone: params.phone, code: params.code});
this.afterLoginAction(result)
} catch (e) {
console.log(e)
}
},
/**
* @description:
*/
async passwordLogin(params: { name: string, password: string }) {
try {
const {result} = await loginPass({username: params.name, password: params.password});
this.afterLoginAction(result)
} catch (e) {
}
},
/**
* @description:
*/
async weChatLogin(params: { code: string }) {
try {
const {result} = await weChatLogin({code: params.code})
this.afterLoginAction(result)
} catch (e) {
console.log(e)
}
},
/**
* @description:
*/
afterLoginAction(value: any) {
this.setUser(value)
if (value[AUTH_KEY]) {
this.setToken(value[AUTH_KEY])
}
authenticationApi({userId: value.userid}).then(({result}) => {
if (result) {
this.setAuth(result)
}
})
},
/**
* @description:
*/
logout() {
this.setToken('')
this.setUser('')
this.setAuth([])
},
},
persist: {
enabled: true,
detached: true,
H5Storage: localStorage
},
});