permission.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { defineStore } from "pinia";
  2. import { store } from "/@/store";
  3. import { cacheType } from "./types";
  4. import { cloneDeep } from "lodash-es";
  5. import { RouteConfigs } from "/@/layout/types";
  6. import { constantMenus } from "/@/router/modules";
  7. import { ascending, filterTree } from "/@/router/utils";
  8. export const usePermissionStore = defineStore({
  9. id: "pure-permission",
  10. state: () => ({
  11. // 静态路由生成的菜单
  12. constantMenus,
  13. // 整体路由生成的菜单(静态、动态)
  14. wholeMenus: [],
  15. // 深拷贝一个菜单树,与导航菜单不突出
  16. menusTree: [],
  17. buttonAuth: [],
  18. // 缓存页面keepAlive
  19. cachePageList: []
  20. }),
  21. actions: {
  22. // 获取异步路由菜单
  23. asyncActionRoutes(routes) {
  24. if (this.wholeMenus.length > 0) return;
  25. this.wholeMenus = filterTree(
  26. ascending(this.constantMenus.concat(routes))
  27. );
  28. this.menusTree = cloneDeep(
  29. filterTree(ascending(this.constantMenus.concat(routes)))
  30. );
  31. const getButtonAuth = (arrRoutes: Array<RouteConfigs>) => {
  32. if (!arrRoutes || !arrRoutes.length) return;
  33. arrRoutes.forEach((v: RouteConfigs) => {
  34. if (v.meta && v.meta.authority) {
  35. this.buttonAuth.push(...v.meta.authority);
  36. }
  37. if (v.children) {
  38. getButtonAuth(v.children);
  39. }
  40. });
  41. };
  42. getButtonAuth(this.wholeMenus);
  43. },
  44. async changeSetting(routes) {
  45. await this.asyncActionRoutes(routes);
  46. },
  47. cacheOperate({ mode, name }: cacheType) {
  48. switch (mode) {
  49. case "add":
  50. this.cachePageList.push(name);
  51. this.cachePageList = [...new Set(this.cachePageList)];
  52. break;
  53. case "delete":
  54. // eslint-disable-next-line no-case-declarations
  55. const delIndex = this.cachePageList.findIndex(v => v === name);
  56. delIndex !== -1 && this.cachePageList.splice(delIndex, 1);
  57. break;
  58. }
  59. },
  60. // 清空缓存页面
  61. clearAllCachePage() {
  62. this.cachePageList = [];
  63. }
  64. }
  65. });
  66. export function usePermissionStoreHook() {
  67. return usePermissionStore(store);
  68. }