Search code examples
vue.jsvue-router

Get children from current route


I have a vuejs 2 project and searching for a way to get the children of the current route (using typescript). Wheather the this.$route nor the this.$router.currentRoute contains a children-prop.

is there any way?

With this information I would like to archive to generate tabs (subviews) automatically.

Update 1

Ok, the solution to get the child-routes is as follows:

this.$router.options.routes?.find((route) => route.name === this.$route.name)?.children

Now the challange is, that comming from a child root I first need to get the parent. Is there any way to also get the parent respectively the get the children of the root-Route?

So I need all children of the current or if available of the parent/root route.

Update 2

Ok, I currently came up with following solution:

this.$router.options.routes?.find((route) => route.name === this.$route.name || route.children?.find((child) => child.name === this.$route.name))?.children

if there is any cleaner/better solution please let me know.


Solution

  • Following my current solution:

    <template>
        <div class="router-tabs">
            <div class="tabs">
                <router-link v-for="(route, index) in childRoutes" :key="index" class="tab" :to="route">
                    {{ route.props.label }}
                </router-link>
            </div>
            <router-view />
        </div>
    </template>
    
    <script lang="ts">
    import { Component, Vue, Prop } from 'vue-property-decorator';
    
    @Component
    export default class RouterTabs extends Vue {
        public get childRoutes() {
            return this.$router.options.routes?.find((route) => route.name === this.$route.name || route.children?.find((child) => child.name === this.$route.name))?.children;
        }
    }
    </script>
    

    that works with following route-config:

    {
        path: '/tabs',
        name: 'Tabs',
        component: Tabs,
        children: [
            {
       
                path: 'test',
                name: 'Test-View',
                component: Test,
                props: { label: 'Test' }
            },
            {
                path: 'test-two',
                name: 'Test-View-Two',
                component: TestTwo,
                props: { label: 'Test12' }
            }
        ]
    },