Files
lingji-work-fe/src/stores/modules/user/index.ts
2025-07-09 16:23:05 +08:00

113 lines
3.1 KiB
TypeScript

import type { RouteRecordNormalized } from 'vue-router';
import { defineStore } from 'pinia';
import { fetchProfileInfo } from '@/api/all/login';
import { useSidebarStore } from '@/stores/modules/side-bar';
import router from '@/router';
import { glsWithCatch, slsWithCatch, rlsWithCatch } from '@/utils/stroage';
interface UserInfo {
id: number;
name: string;
head_image: String;
current_enterprise_id: number;
mobile: string;
// 添加其他用户属性...
}
interface UserState {
token: string;
userInfo: UserInfo | null;
allowAccessRoutes: RouteRecordNormalized[];
// isLogin: boolean;
}
interface UserInfo {
id: number;
mobile: string;
name: string;
}
export const useUserStore = defineStore('user', {
state: (): UserState => ({
token: glsWithCatch('accessToken') || '',
userInfo: (glsWithCatch('userInfo') && JSON.parse(glsWithCatch('userInfo') as string)) || null,
allowAccessRoutes:
(glsWithCatch('allowAccessRoutes') && JSON.parse(glsWithCatch('allowAccessRoutes') as string)) || [], // 允许访问的路由列表
}),
getters: {
isLogin(): boolean {
return !!this.token;
},
},
actions: {
// 设置 Token
setToken(token: string) {
this.token = `Bearer ${token}`;
slsWithCatch('accessToken', this.token);
},
deleteToken() {
this.token = '';
rlsWithCatch('accessToken');
},
// 获取 Token
getToken() {
return this.token;
},
// 设置用户信息
setUserInfo(userInfo: UserInfo | null) {
this.userInfo = userInfo;
slsWithCatch('userInfo', JSON.stringify(userInfo));
},
clearUserInfo() {
this.userInfo = null;
rlsWithCatch('userInfo');
},
// 获取用户信息
async getUserInfo() {
const { code, data } = await fetchProfileInfo();
if (code === 200) {
this.setUserInfo(data);
}
},
clearUserAllowAccessRoutes() {
this.allowAccessRoutes = [];
rlsWithCatch('allowAccessRoutes');
},
getUserAllowAccessRoutes() {
const sidebarStore = useSidebarStore();
const menuList = sidebarStore.menuList;
const appRoutes = router.getRoutes();
appRoutes.forEach((route: any) => {
if (!route.meta?.requiresAuth) {
this.allowAccessRoutes.push(route);
}
});
const pushAllowAccessRoutes = (pathNames: string[]) => {
const matchedRoute = appRoutes.filter((route: any) => pathNames.includes(route.name));
this.allowAccessRoutes.push(...matchedRoute);
};
menuList.forEach((item) => {
if (item.children && item.children.length > 0) {
item.children.forEach((child: any) => {
pushAllowAccessRoutes(child.pathNames);
});
} else {
pushAllowAccessRoutes(item.pathNames);
}
});
this.allowAccessRoutes = uniqBy(this.allowAccessRoutes, 'name');
slsWithCatch('allowAccessRoutes', JSON.stringify(this.allowAccessRoutes));
},
},
});