permission.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { defineStore } from "pinia";
  2. import {
  3. type cacheType,
  4. store,
  5. debounce,
  6. ascending,
  7. getKeyList,
  8. filterTree,
  9. constantMenus,
  10. filterNoPermissionTree,
  11. formatFlatteningRoutes
  12. } from "../utils";
  13. import { useMultiTagsStoreHook } from "./multiTags";
  14. export const usePermissionStore = defineStore("pure-permission", {
  15. state: () => ({
  16. // 静态路由生成的菜单
  17. constantMenus,
  18. // 整体路由生成的菜单(静态、动态)
  19. wholeMenus: [],
  20. // 整体路由(一维数组格式)
  21. flatteningRoutes: [],
  22. // 缓存页面keepAlive
  23. cachePageList: []
  24. }),
  25. actions: {
  26. /** 组装整体路由生成的菜单 */
  27. handleWholeMenus(routes: any[]) {
  28. this.wholeMenus = filterNoPermissionTree(
  29. filterTree(ascending(this.constantMenus.concat(routes)))
  30. );
  31. this.flatteningRoutes = formatFlatteningRoutes(
  32. this.constantMenus.concat(routes) as any
  33. );
  34. },
  35. cacheOperate({ mode, name }: cacheType) {
  36. const delIndex = this.cachePageList.findIndex(v => v === name);
  37. switch (mode) {
  38. case "refresh":
  39. this.cachePageList = this.cachePageList.filter(v => v !== name);
  40. break;
  41. case "add":
  42. this.cachePageList.push(name);
  43. break;
  44. case "delete":
  45. delIndex !== -1 && this.cachePageList.splice(delIndex, 1);
  46. break;
  47. }
  48. /** 监听缓存页面是否存在于标签页,不存在则删除 */
  49. debounce(() => {
  50. let cacheLength = this.cachePageList.length;
  51. const nameList = getKeyList(useMultiTagsStoreHook().multiTags, "name");
  52. while (cacheLength > 0) {
  53. nameList.findIndex(v => v === this.cachePageList[cacheLength - 1]) ===
  54. -1 &&
  55. this.cachePageList.splice(
  56. this.cachePageList.indexOf(this.cachePageList[cacheLength - 1]),
  57. 1
  58. );
  59. cacheLength--;
  60. }
  61. })();
  62. },
  63. /** 清空缓存页面 */
  64. clearAllCachePage() {
  65. this.wholeMenus = [];
  66. this.cachePageList = [];
  67. }
  68. }
  69. });
  70. export function usePermissionStoreHook() {
  71. return usePermissionStore(store);
  72. }