cpms_operation_platform/src/hooks/useBreadcrumb.ts

68 lines
2.0 KiB
TypeScript
Raw Normal View History

2026-07-14 10:31:17 +08:00
import { computed, h } from 'vue';
import { useRoute, useRouter } from 'vue-router';
export function useBreadcrumb() {
const route = useRoute();
const router = useRouter();
/**
*
*/
const buildPath = (currentPath: string, recordPath: string): string => {
if (recordPath.startsWith('/')) {
return recordPath;
}
return currentPath ? `${currentPath}/${recordPath}`.replace(/\/+/g, '/') : `/${recordPath}`;
};
const breadcrumbs = computed(() => {
const matched = route.matched;
const items: Array<{ title: string; path?: string }> = [];
let currentPath = '';
for (const record of matched) {
currentPath = buildPath(currentPath, record.path);
if (record.meta && record.meta.title) {
items.push({
title: record.meta.title as string,
path: currentPath,
});
}
}
return items;
});
const breadcrumbItems = computed(() => {
return breadcrumbs.value.map((item, index) => ({
key: index,
title:
item.path && index !== breadcrumbs.value.length - 1
? h(
'a',
{
onClick: (e: Event) => {
e.preventDefault();
// 最保守方案:只有当前路径包含 /bracket/ 且目标路径是 /events/bracket 时才保留 query
// 也就是只有:/events/bracket/xxx → /events/bracket 时才保留
const targetPath = item.path || '/';
const isBracketChildPage =
route.path.includes('/bracket/') && targetPath === '/events/bracket';
router.push({
path: targetPath,
query: isBracketChildPage ? route.query : {},
});
},
},
item.title,
)
: item.title,
}));
});
return {
breadcrumbs,
breadcrumbItems,
};
}