2021-08-13 14:22:35 +08:00
|
|
|
import { defineStore } from 'pinia';
|
2021-09-07 11:57:35 +08:00
|
|
|
import { store } from '@/store';
|
2021-12-12 17:28:39 +08:00
|
|
|
import { clearAuthStorage, getToken, getUserInfo } from '@/utils';
|
2021-08-13 14:22:35 +08:00
|
|
|
import type { UserInfo } from '@/interface';
|
2021-05-29 03:02:15 +08:00
|
|
|
|
|
|
|
interface AuthState {
|
2021-08-13 14:22:35 +08:00
|
|
|
/** 用户token */
|
2021-05-29 03:02:15 +08:00
|
|
|
token: string;
|
2021-08-13 14:22:35 +08:00
|
|
|
/** 用户信息 */
|
2021-05-29 03:02:15 +08:00
|
|
|
userInfo: UserInfo;
|
|
|
|
}
|
|
|
|
|
2021-08-13 14:22:35 +08:00
|
|
|
const authStore = defineStore({
|
|
|
|
/** 区分不通状态的唯一标识 */
|
|
|
|
id: 'auth-store',
|
|
|
|
/** 状态 */
|
|
|
|
state: (): AuthState => {
|
|
|
|
return {
|
2021-12-12 17:28:39 +08:00
|
|
|
token: getToken(),
|
|
|
|
userInfo: getUserInfo()
|
2021-08-13 14:22:35 +08:00
|
|
|
};
|
|
|
|
},
|
|
|
|
getters: {
|
|
|
|
/** 是否登录 */
|
|
|
|
isLogin: state => Boolean(state.token)
|
|
|
|
},
|
|
|
|
actions: {
|
2021-12-12 17:28:39 +08:00
|
|
|
/** 设置Auth状态 */
|
|
|
|
setAuthState(data: Partial<AuthState>) {
|
|
|
|
Object.assign(this, data);
|
|
|
|
},
|
2021-08-13 14:22:35 +08:00
|
|
|
/** 重置auth状态 */
|
|
|
|
resetAuthState() {
|
2021-12-12 17:28:39 +08:00
|
|
|
clearAuthStorage();
|
2021-08-13 14:22:35 +08:00
|
|
|
this.$reset();
|
2021-12-12 17:28:39 +08:00
|
|
|
},
|
|
|
|
/** 判断用户权益是否变更 */
|
|
|
|
getIsAuthChange() {
|
|
|
|
const token = getToken();
|
|
|
|
const tokenChange = token !== this.token;
|
|
|
|
return tokenChange;
|
2021-05-29 03:02:15 +08:00
|
|
|
}
|
2021-08-13 14:22:35 +08:00
|
|
|
}
|
|
|
|
});
|
2021-05-29 03:02:15 +08:00
|
|
|
|
2021-08-13 14:22:35 +08:00
|
|
|
export default function useAuthStore() {
|
|
|
|
return authStore(store);
|
2021-05-29 03:02:15 +08:00
|
|
|
}
|