houzhongjian
2024-12-05 2717813966ced88c6a1635663dd01b502158a1b8
提交 | 用户 | 时间
820397 1 import { defineStore } from 'pinia'
H 2 import { store } from '@/store'
3 import { cloneDeep } from 'lodash-es'
4 import remainingRouter from '@/router/modules/remaining'
5 import { flatMultiLevelRoutes, generateRoute } from '@/utils/routerHelper'
271781 6 import {CACHE_KEY, useSessionCache} from '@/hooks/web/useCache'
820397 7
271781 8 const { wsSessionCache } = useSessionCache()
820397 9
H 10 export interface PermissionState {
11   routers: AppRouteRecordRaw[]
12   addRouters: AppRouteRecordRaw[]
13   menuTabRouters: AppRouteRecordRaw[]
14 }
15
16 export const usePermissionStore = defineStore('permission', {
17   state: (): PermissionState => ({
18     routers: [],
19     addRouters: [],
20     menuTabRouters: []
21   }),
22   getters: {
23     getRouters(): AppRouteRecordRaw[] {
24       return this.routers
25     },
26     getAddRouters(): AppRouteRecordRaw[] {
27       return flatMultiLevelRoutes(cloneDeep(this.addRouters))
28     },
29     getMenuTabRouters(): AppRouteRecordRaw[] {
30       return this.menuTabRouters
31     }
32   },
33   actions: {
34     async generateRoutes(): Promise<unknown> {
35       return new Promise<void>(async (resolve) => {
36         // 获得菜单列表,它在登录的时候,setUserInfoAction 方法中已经进行获取
37         let res: AppCustomRouteRecordRaw[] = []
271781 38         if (wsSessionCache.get(CACHE_KEY.ROLE_ROUTERS)) {
H 39           res = wsSessionCache.get(CACHE_KEY.ROLE_ROUTERS) as AppCustomRouteRecordRaw[]
820397 40         }
H 41         const routerMap: AppRouteRecordRaw[] = generateRoute(res)
42         // 动态路由,404一定要放到最后面
43         this.addRouters = routerMap.concat([
44           {
45             path: '/:path(.*)*',
46             redirect: '/404',
47             name: '404Page',
48             meta: {
49               hidden: true,
50               breadcrumb: false
51             }
52           }
53         ])
54         // 渲染菜单的所有路由
55         this.routers = cloneDeep(remainingRouter).concat(routerMap)
56         resolve()
57       })
58     },
59     setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
60       this.menuTabRouters = routers
61     }
62   },
63   persist: false
64 })
65
66 export const usePermissionStoreWithOut = () => {
67   return usePermissionStore(store)
68 }