import { useRouter } from 'vue-router'; import { defineStore } from 'pinia'; import { fetchProfileInfo } from '@/api/all/login'; import { useSidebarStore } from '@/stores/modules/side-bar'; 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: string[]; // 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); }, clearToken() { 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 router = useRouter(); const menuList = sidebarStore.menuList; const appRoutes = router.options.routes; appRoutes.forEach((route: any) => { if (!route.meta?.requiresAuth) { this.allowAccessRoutes.push(route.name); } }); const pushAllowAccessRoutes = (includeRouteNames: string[]) => { const matchedRoute = appRoutes .filter((route: any) => includeRouteNames.includes(route.name)) .map((route: any) => route.name); this.allowAccessRoutes.push(...matchedRoute); }; menuList.forEach((item) => { if (item.children && item.children.length > 0) { item.children.forEach((child: any) => { pushAllowAccessRoutes(child.includeRouteNames); }); } else { pushAllowAccessRoutes(item.includeRouteNames); } }); this.allowAccessRoutes = uniq(this.allowAccessRoutes); slsWithCatch('allowAccessRoutes', JSON.stringify(this.allowAccessRoutes)); }, }, });