[Vuejs]-Get children from current route

0👍

✅

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

0👍

I am doing this in Vue 3 to get child routes of a certain menu item:

  import { useRoute, useRouter } from 'vue-router'

  const $route = useRoute()
  const $router = useRouter()

  function getChildRoutes() {
    const routes = $router.options.routes
    const route = routes.find(item => item.path.split('/')[1] === $route.path.split('/')[1])
    let childRoutes = []
    if (route.children) {
      childRoutes = route.children
        .filter(r => r.path && !r.path.startsWith(':'))
        .map(r => ({name: r.name, href: route.path + '/' + r.path}))
    }
    return childRoutes
  }

Leave a comment