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, }; }