hooks.tsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import {onMounted, reactive, watch} from 'vue';
  2. import {useTabStore, storeToRefs} from '@stores';
  3. import {find} from 'lodash-es';
  4. import {useRoute, useRouter} from 'vue-router';
  5. import {formatMenu} from '@utils';
  6. import {useQueryClient} from '@tanstack/vue-query';
  7. import {MenuListData} from '@models';
  8. import {getMenuByUserId} from '@apis';
  9. export function useMenu() {
  10. const queryClient = useQueryClient();
  11. const data = queryClient.getQueryData<MenuListData[]>([getMenuByUserId.name]);
  12. const basicMenu = [
  13. {
  14. name: '首页',
  15. koreanName: '첫 페이지',
  16. id: '-1',
  17. img: 'HomeMenuIcon',
  18. pid: '0',
  19. url: '/main',
  20. orderBy: '',
  21. modifyTime: '',
  22. modifyUser: '',
  23. },
  24. ...(data ?? []),
  25. ];
  26. const menuOptions = formatMenu(basicMenu);
  27. const tabStore = useTabStore();
  28. const {activeKey, tabList} = storeToRefs(tabStore);
  29. const expandKeys = reactive<string[]>([]);
  30. const {push} = useRouter();
  31. function onExpandedUpdate(keys: string[] | string) {
  32. expandKeys.length = 0;
  33. expandKeys.push(...(Array.isArray(keys) ? keys : [keys]));
  34. }
  35. function onUpdate(
  36. key: string,
  37. item: typeof menuOptions[0],
  38. ) {
  39. const {label, pid, url, koLabel} = item;
  40. tabStore.dispatch({
  41. type: 'ADD',
  42. payload: {label, key, url, pid, koLabel},
  43. });
  44. }
  45. const route = useRoute();
  46. onMounted(function() {
  47. // 页面初始页面不一定是首页需要判断是否需要增加tab
  48. const idx = basicMenu.findIndex(val => val.url === route.path);
  49. if (idx < 0) return;
  50. const {name, pid, url, id, koreanName} = basicMenu[idx];
  51. tabStore.dispatch({
  52. type: 'ADD',
  53. payload: {label: name, key: id, url, pid, koLabel: koreanName},
  54. });
  55. });
  56. // activeKey变化后更新菜单的展开菜单的值并跳转到对应的url
  57. watch(activeKey, function(value) {
  58. if (expandKeys[0] === value) return;
  59. const temp = find(
  60. tabList.value,
  61. val => val.key === value,
  62. );
  63. if (!temp) return;
  64. onExpandedUpdate(temp.pid);
  65. push(temp.url);
  66. });
  67. return [
  68. {activeKey, expandKeys, menuOptions},
  69. {onUpdate, onExpandedUpdate},
  70. ] as const;
  71. }