permission.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { defineStore } from "pinia";
  2. import { store } from "@/store";
  3. import type { cacheType } from "./types";
  4. import { constantMenus } from "@/router";
  5. import { useMultiTagsStoreHook } from "./multiTags";
  6. import { debounce, getKeyList } from "@pureadmin/utils";
  7. import { ascending, filterTree, filterNoPermissionTree } from "@/router/utils";
  8. export const usePermissionStore = defineStore({
  9. id: "pure-permission",
  10. state: () => ({
  11. // 静态路由生成的菜单
  12. constantMenus,
  13. // 整体路由生成的菜单(静态、动态)
  14. wholeMenus: [],
  15. // 缓存页面keepAlive
  16. cachePageList: []
  17. }),
  18. actions: {
  19. /** 组装整体路由生成的菜单 */
  20. handleWholeMenus(routes: any[]) {
  21. this.wholeMenus = filterNoPermissionTree(
  22. filterTree(ascending(this.constantMenus.concat(routes)))
  23. );
  24. // 代码删除
  25. this.wholeMenus = this.wholeMenus.reduce((accumulator, current) => {
  26. const x = accumulator.find(item => item.path === current.path);
  27. if (!x) {
  28. return accumulator.concat([current]);
  29. } else {
  30. return accumulator;
  31. }
  32. }, []);
  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. }