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.
CodePudding user response:
I found this solution you can try like following:
computed: {
routeChildren() {
const matched = this.$route.matched;
const routePath = matched[matched.length - 1].path;
return this.getChildrenByPath(routePath);
},
},
methods: {
getChildrenByPath(path) {
let children = this.$router.options.routes;
if (path) {
// clean up empty elements
let chunks = path.split('/');
chunks = chunks.filter((chunk) => chunk !== '');
if (chunks.length) {
chunks.forEach((chunk, index) => {
let path = chunk;
if (index === 0) path = `/${path}`;
if (children) {
const found = children.find((child) => child.path === path);
if (found) {
children = found.children;
}
}
});
}
}
return children;
},
},
CodePudding user response:
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' }
}
]
},