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

Vue2 + TypeScript 项目中获取当前路由对应父/根路由子路由的方法

解决方案

核心原理说明

this.$route 和 this.$router.currentRoute 是当前激活路由的运行时实例,仅包含当前路由的状态信息,路由配置的children属性存储在$router.options.routes的静态配置中。另外Vue Router提供了$route.matched 官方API,是从根路由到当前路由的所有匹配配置的有序数组,是实现需求的最优选择。


方案1:通用场景(适配任意嵌套层级)

需求A:获取当前路由自身配置的子路由

// matched最后一项即为当前路由的完整配置
const currentRouteConf = this.$route.matched[this.$route.matched.length - 1]
const currentChildren = currentRouteConf?.children || []

需求B:获取当前路由所属父路由的所有子路由(即同级路由,用于生成平级标签页)

const matched = this.$route.matched
// 存在父路由则取倒数第二项的配置,否则取根路由配置
const parentRouteConf = matched.length > 1 ? matched[matched.length - 2] : matched[0]
const siblingRoutes = parentRouteConf?.children || []

方案2:嵌套层级不固定的场景

如果项目路由嵌套层级不固定,只有特定层级的路由需要生成子标签页,可以给对应父路由的meta加自定义标识:

// 路由配置示例
{
  name: 'Dashboard',
  path: '/dashboard',
  meta: { isTabRoot: true }, // 新增标识
  children: [/* 子路由列表 */]
}

获取子路由代码:

const tabRoot = this.$route.matched.find(item => item.meta?.isTabRoot)
const tabRoutes = tabRoot?.children || []

优化说明

你之前的实现仅支持最多2层嵌套的路由,且需要全量遍历整个路由表,路由条目较多时性能较差。使用$route.matched无需遍历全量路由,仅需处理当前路由的匹配层级(通常不超过5层),性能更优,且适配任意深度的路由嵌套。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:27:03