You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何校验浏览器URL/路由与路径掩码关联?实现菜单标记ID规则

实现基于路由data.id的菜单激活状态校验

需求概述

需要创建一套ID规则,用于在HTML中通过类别ID标记菜单。核心逻辑是:验证当前访问的URL是否与路由配置中对应data.id的路由匹配——若当前URL匹配该路由的路径,且路由data.id与传入的菜单ID一致,则返回true,标记该菜单为激活状态。

示例:当访问page/id/1234时,需识别出对应路由的data.id='page-data-x',传入该ID的菜单应返回true。

现有路由模块结构

{
    path: 'page',
    children: [
        {
            path: 'id/:id',
            component: PageComponent,
            canActivate: [AuthGuard],
            data: {
                id: 'page-data-x',
            }
        },
        {
            path: 'category/:id/id/:id',
            component: PageComponent,
            canActivate: [AuthGuard],
            data: {
                id: 'page-data-y',
            }
        }
    ]
}

当前初始化代码

已在组件构造函数中获取当前路由的data.id和URL:

contentID: any; 
currentURL: string;

constructor(
    private router: Router, 
    private route: ActivatedRoute
) {
    // 获取路由data中的id
    this.contentID = this.route.snapshot.data?.id;
    // 获取当前URL
    this.currentURL = this.router.url;
}

尝试过但失败的实现代码

isActiveRoute(type: string): boolean {
    // 生成目标路由字符串
    const targetRoute = this.routerLink(type);
    const targetRouteString = Array.isArray(targetRoute) ? targetRoute
        .filter(segment => typeof segment !== 'object')
        .join('/')
        .replace(/\/\//gi, '/') : targetRoute;

    const currentRoute = this.router.url.split('?')[0].split(';')[0];

    const children = (this.route.snapshot.routeConfig?.children || []).filter(
        (child) => child.data?.id
    );

    const isMatchingPath = (child: any): boolean => {
        if(child.path) {
            const regexPattern = '^' + child.path.replace(/:[^/]+/g, '[^/]+') + '$';
            const regex = new RegExp(regexPattern);
            return regex.test(currentRoute) && child.data?.id === type;
        }
    };

    const matchingChild = children.find(child => isMatchingPath(child));

    if (matchingChild) {
        return true;
    }

    const routeDataId = this.route.snapshot.data?.id;
    const routePath = this.route.snapshot.routeConfig?.path;

    if (routeDataId === type && routePath && currentRoute.includes(routePath)) {
        return true;
    }

    return currentRoute.includes(targetRouteString);
}

routerLink(type: string) {
    this.queryParams = this.routerParams[type];

    switch (type) {
        case 'dashboard':
            return ['page', 'dashboard'];
        // 其他case省略
    }
}

寻求解决方案

需要正确实现URL与路由路径掩码的校验逻辑,确保能准确匹配当前URL对应的路由data.id,从而正确标记菜单的激活状态。

内容的提问来源于stack exchange,提问作者Ivan Ferrer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 13:42:41