拆分菜单 通过url区分访问
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
lnljyang
2026-05-14 17:33:01 +08:00
parent 0dc45504f2
commit fdef0a940a
8 changed files with 271 additions and 144 deletions

View File

@@ -10,29 +10,20 @@ export interface ModuleConfig {
component: ComponentType;
}
/** path 到模块 id 的映射 */
const PATH_MAP: Record<string, string> = {
'/vehicle': 'assets',
'/assets': 'assets',
'/mileage': 'mileage',
'/scheduling': 'scheduling',
'/energy': 'energy',
};
/** hash 一级段(`#<id>` 或 `#<id>/<sub>` 都只取 id */
function getHashHead(): string {
return window.location.hash.slice(1).split('/')[0];
}
function getInitialModule(modules: ModuleConfig[]): string {
// 优先看 hash
const hash = window.location.hash.slice(1);
if (modules.some((m) => m.id === hash)) return hash;
// 再看 pathname
const pathModule = PATH_MAP[window.location.pathname];
if (pathModule && modules.some((m) => m.id === pathModule)) return pathModule;
// 默认第一个
const head = getHashHead();
if (modules.some((m) => m.id === head)) return head;
return modules[0]?.id ?? '';
}
function getHashModule(modules: ModuleConfig[]): string {
const hash = window.location.hash.slice(1);
return modules.some((m) => m.id === hash) ? hash : '';
const head = getHashHead();
return modules.some((m) => m.id === head) ? head : '';
}
export function Shell({ modules }: { modules: ModuleConfig[] }) {
@@ -48,16 +39,17 @@ export function Shell({ modules }: { modules: ModuleConfig[] }) {
}, [modules]);
useEffect(() => {
// 同步 hash 到当前模块:使用 replaceState 避免产生多余的 history 记录,
// 否则在小程序/webview 环境下首次进入需要点两次返回才能退出
if (window.location.hash.slice(1) !== activeModule) {
// 同步 hash 一段到当前模块:使用 replaceState 避免产生多余的 history 记录,
// 否则在小程序/webview 环境下首次进入需要点两次返回才能退出
// 注意只比对一级段,避免把子模块写入的 `#<id>/<sub>` 二级段抹掉。
if (getHashHead() !== activeModule) {
const { pathname, search } = window.location;
window.history.replaceState(null, '', `${pathname}${search}#${activeModule}`);
}
}, [activeModule]);
const switchModule = (id: string) => {
if (window.location.hash.slice(1) === id) return;
if (getHashHead() === id) return;
const { pathname, search } = window.location;
window.history.replaceState(null, '', `${pathname}${search}#${id}`);
setActiveModule(id);