Damon
Damon

Reputation: 10809

Can a component know its child-routes in vue-router

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

I want Main to know what child routes are defined for it.

I created a function to crawl around the overall routes object and figure it out, but its evaluated differently depending on this.$router.currentRoute which makes it verbose and terrifying and more complicated the more path options there are in the children. Is there a straightforward way for the parent component to know where it is within the routes and have a list of its children?

IE in the main component how to I tell how many children I have and which of them is currently active?

Upvotes: 5

Views: 6822

Answers (2)

Gass
Gass

Reputation: 9344

You can do so by looping through the nested routes this.$router.options.routes you desire to extract and then push them into an array when the component is mounted()

Note: I'm using Vue Class Component library that's why the code looks like this. But the same logic can be applied to Options API and Components API

routeName = 'randomName'
pathNames = []


mounted(){
    const routes = this.$router.options.routes

    for (const route of routes) {
        if (route.name === routeName) {
            for (const children of route.children) {
                this.pathNames.push(children.name)
            }
        }
    }
}

Upvotes: 2

AndrewShmig
AndrewShmig

Reputation: 4923

Will this solve your problem? Here is a sample codepen. Everything you need to know and set - route name (even more - you can instead use meta or even path properties). You can even create recursive function which will search for every route including every children array.

Here is a simple function to search for child components knowing parent path name:

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);
  }
}

Can be called like so:

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

Called on sample routes object:

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},
      ],
    },
  ]

will return:

[Object { name: "subone", path: "1.1", component: {…} }]

Upvotes: 2

Related Questions