vue-vben-admin/src/layouts/default/multitabs/useMultipleTabs.ts

85 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-12-03 21:49:32 +08:00
import Sortable from 'sortablejs';
import { toRaw, ref, nextTick, onMounted } from 'vue';
import { RouteLocationNormalized } from 'vue-router';
import { useProjectSetting } from '/@/hooks/setting';
2020-11-25 21:26:10 +08:00
import router from '/@/router';
2020-12-03 21:49:32 +08:00
import { tabStore } from '/@/store/modules/tab';
import { isNullAndUnDef } from '/@/utils/is';
2020-11-25 21:26:10 +08:00
2020-12-03 21:49:32 +08:00
export function initAffixTabs(): string[] {
const affixList = ref<RouteLocationNormalized[]>([]);
2020-11-25 21:26:10 +08:00
/**
* @description: Filter all fixed routes
*/
2020-12-03 21:49:32 +08:00
function filterAffixTabs(routes: RouteLocationNormalized[]) {
const tabs: RouteLocationNormalized[] = [];
2020-11-25 21:26:10 +08:00
routes &&
routes.forEach((route) => {
if (route.meta && route.meta.affix) {
2020-12-03 21:49:32 +08:00
tabs.push(toRaw(route));
2020-11-25 21:26:10 +08:00
}
});
return tabs;
}
/**
* @description: Set fixed tabs
*/
function addAffixTabs(): void {
2020-12-03 21:49:32 +08:00
const affixTabs = filterAffixTabs((router.getRoutes() as unknown) as RouteLocationNormalized[]);
2020-11-25 22:28:58 +08:00
affixList.value = affixTabs;
2020-11-25 21:26:10 +08:00
for (const tab of affixTabs) {
2020-12-03 21:49:32 +08:00
tabStore.addTabAction(({
meta: tab.meta,
name: tab.name,
path: tab.path,
} as unknown) as RouteLocationNormalized);
2020-11-25 21:26:10 +08:00
}
}
2020-11-25 22:28:58 +08:00
2020-11-25 21:26:10 +08:00
let isAddAffix = false;
if (!isAddAffix) {
addAffixTabs();
isAddAffix = true;
}
2020-11-25 22:28:58 +08:00
return affixList.value.map((item) => item.meta?.title).filter(Boolean);
2020-11-25 21:26:10 +08:00
}
2020-12-03 21:49:32 +08:00
export function useTabsDrag(affixTextList: string[]) {
const { multiTabsSetting } = useProjectSetting();
function initSortableTabs() {
if (!multiTabsSetting.canDrag) return;
nextTick(() => {
const el = document.querySelectorAll(
'.multiple-tabs .ant-tabs-nav > div'
)?.[0] as HTMLElement;
if (!el) return;
Sortable.create(el, {
animation: 500,
delay: 400,
delayOnTouchOnly: true,
filter: (e: ChangeEvent) => {
const text = e?.target?.innerText;
if (!text) return false;
return affixTextList.includes(text);
},
onEnd: (evt) => {
const { oldIndex, newIndex } = evt;
if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || oldIndex === newIndex) {
return;
}
tabStore.commitSortTabs({ oldIndex, newIndex });
},
});
});
}
onMounted(() => {
initSortableTabs();
});
}