useMultipleTabs.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { toRaw, ref, nextTick } from 'vue';
  2. import type { RouteLocationNormalized } from 'vue-router';
  3. import { useDesign } from '/@/hooks/web/useDesign';
  4. import { useSortable } from '/@/hooks/web/useSortable';
  5. import { useMultipleTabStore } from '/@/store/modules/multipleTab';
  6. import { isNullAndUnDef } from '/@/utils/is';
  7. import projectSetting from '/@/settings/projectSetting';
  8. import { useRouter } from 'vue-router';
  9. export function initAffixTabs(): string[] {
  10. const affixList = ref<RouteLocationNormalized[]>([]);
  11. const tabStore = useMultipleTabStore();
  12. const router = useRouter();
  13. /**
  14. * @description: Filter all fixed routes
  15. */
  16. function filterAffixTabs(routes: RouteLocationNormalized[]) {
  17. const tabs: RouteLocationNormalized[] = [];
  18. routes &&
  19. routes.forEach((route) => {
  20. if (route.meta && route.meta.affix) {
  21. tabs.push(toRaw(route));
  22. }
  23. });
  24. return tabs;
  25. }
  26. /**
  27. * @description: Set fixed tabs
  28. */
  29. function addAffixTabs(): void {
  30. const affixTabs = filterAffixTabs(router.getRoutes() as unknown as RouteLocationNormalized[]);
  31. affixList.value = affixTabs;
  32. for (const tab of affixTabs) {
  33. tabStore.addTab({
  34. meta: tab.meta,
  35. name: tab.name,
  36. path: tab.path,
  37. } as unknown as RouteLocationNormalized);
  38. }
  39. }
  40. let isAddAffix = false;
  41. if (!isAddAffix) {
  42. addAffixTabs();
  43. isAddAffix = true;
  44. }
  45. return affixList.value.map((item) => item.meta?.title).filter(Boolean) as string[];
  46. }
  47. export function useTabsDrag(affixTextList: string[]) {
  48. const tabStore = useMultipleTabStore();
  49. const { multiTabsSetting } = projectSetting;
  50. const { prefixCls } = useDesign('multiple-tabs');
  51. nextTick(() => {
  52. if (!multiTabsSetting.canDrag) return;
  53. const el = document.querySelectorAll(
  54. `.${prefixCls} .ant-tabs-nav-wrap > div`,
  55. )?.[0] as HTMLElement;
  56. const { initSortable } = useSortable(el, {
  57. filter: (e: ChangeEvent) => {
  58. const text = e?.target?.innerText;
  59. if (!text) return false;
  60. return affixTextList.includes(text);
  61. },
  62. onEnd: (evt) => {
  63. const { oldIndex, newIndex } = evt;
  64. if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || oldIndex === newIndex) {
  65. return;
  66. }
  67. tabStore.sortTabs(oldIndex, newIndex);
  68. },
  69. });
  70. initSortable();
  71. });
  72. }