组件可以知道 vue-router 中的子路由吗

2024-04-13

<Main>
  <router-view></router-view>
</Main>
[
  {
    path: '/',
    component: Intro,
  },
  {
    path: '/path1',
    component: Main,
    children: [{},{},{}]
  },
  {
    path: '/path2',
    component: Main,
    children: [{},{},{},{},{}]
  }
]

I want Main了解为其定义了哪些子路由。

我创建了一个函数来爬行整个路线对象并找出它,但它的评估方式不同,具体取决于this.$router.currentRoute这使得孩子们的路径选择越多,它就越冗长、可怕、越复杂。有没有一种简单的方法可以让父组件知道它在路由中的位置并拥有其子组件的列表?

IE 在主要组件中如何知道我有多少个孩子以及其中哪些当前处于活动状态?


这能解决您的问题吗?这里有一个示例代码笔 https://codepen.io/anon/pen/MLrpmR。您需要了解和设置的所有内容 - 路线名称(甚至更多 - 您可以改为使用meta甚至path特性)。您甚至可以创建递归函数,它将搜索每条路线,包括每条路线children array.

这是一个简单的函数,用于搜索知道父路径名的子组件:

function recursiveChildrenSearch(routes, name) {
  for (let route of routes) {
    if (route.name === name)
      return route.children;
    else if (route.children.length > 0)
      return recursiveChildrenSearch(route.children, name);
  }
}

可以这样调用:

recursiveChildrenSearch(router.options.routes, "one")

调用示例路由对象:

routes: [
    {
      path: '/hello',
      name: "main",
      component: A,
      children: [
        {name: 'one', path: '1', component: B, 
          children: [
              {name: 'subone', path: '1.1', component: C}
          ]},
        {name: 'two', path: '2', component: C},
      ],
    },
  ]

将返回:

[Object { name: "subone", path: "1.1", component: {…} }]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

组件可以知道 vue-router 中的子路由吗 的相关文章

随机推荐