代码之家  ›  专栏  ›  技术社区  ›  Damon

组件能否知道其在vue路由器中的子路由

  •  1
  • Damon  · 技术社区  · 6 年前
    <Main>
      <router-view></router-view>
    </Main>
    
    [
      {
        path: '/',
        component: Intro,
      },
      {
        path: '/path1',
        component: Main,
        children: [{},{},{}]
      },
      {
        path: '/path2',
        component: Main,
        children: [{},{},{},{},{}]
      }
    ]
    

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

    我创建了一个函数来爬过整个routes对象并找出它,但它的计算方式会根据具体情况而有所不同 this.$router.currentRoute 这使得它冗长、可怕,而且孩子们的路径选择越多,就越复杂。是否有一种简单的方法让父组件知道它在路由中的位置并拥有其子组件的列表?

    IE在主要部分中,我如何告诉我有多少个孩子,以及他们中的哪一个目前处于活动状态?

    1 回复  |  直到 6 年前
        1
  •  0
  •   AndrewShmig    6 年前

    sample codepen . 您需要知道和设置的所有信息-路由名称(甚至更多-您可以使用 meta 甚至 path children 大堆

    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: {…} }]