Files
lingji-work-fe/src/stores/modules/side-bar/index.ts
2025-07-08 16:55:04 +08:00

76 lines
2.3 KiB
TypeScript

/*
* @Author: RenXiaoDong
* @Date: 2025-06-23 22:13:30
*/
import { defineStore } from 'pinia';
import router from '@/router';
import type { RouteLocationNormalized } from 'vue-router';
import { MENU_LIST } from './constants';
import { useEnterpriseStore } from '@/stores/modules/enterprise';
interface sidebarState {
activeMenuId: number | null;
menuList: any[];
allowAccessRoutes: any[];
}
export const useSidebarStore = defineStore('sidebar', {
state: (): sidebarState => ({
activeMenuId: null,
menuList: [],
allowAccessRoutes: [], // 允许访问的路由列表
}),
actions: {
clearActiveMenuId() {
this.activeMenuId = null;
},
setActiveMenuId(id: number) {
this.activeMenuId = id;
},
clearUserNavbarMenuList() {
this.menuList = [];
},
// navbar菜单列表由企业对应权限决定
getUserNavbarMenuList() {
const enterpriseStore = useEnterpriseStore();
this.menuList = MENU_LIST.filter(
(item) => !item.permissionKey || enterpriseStore.enterpriseInfo?.permissions?.includes(item.permissionKey),
);
},
// 根据当前路由自动设置 activeMenuId
setActiveMenuIdByRoute(route: RouteLocationNormalized) {
const appRoutes = router.options?.routes ?? [];
// 查找当前路由所属的菜单组
const findMenuGroup = (routes: any[]): number | null => {
for (const routeItem of routes) {
// 检查子路由
if (routeItem.children?.length > 0) {
// 检查当前路由是否是这个父路由的子路由
const isChildRoute = routeItem.children.some((child: any) => child.name === route.name);
if (isChildRoute) {
return routeItem.meta?.id || null;
}
// 递归检查更深层的子路由
const childResult = findMenuGroup(routeItem.children);
if (childResult !== null) {
return routeItem.meta?.id || childResult;
}
} else {
if (routeItem.name === route.name) {
return routeItem.meta?.id || null;
}
}
}
return null;
};
const menuId = findMenuGroup(appRoutes as any);
if (menuId !== null) {
this.activeMenuId = menuId;
}
},
},
});