首页 > 解决方案 > 从当前路线获取孩子

问题描述

我有一个 vuejs 2 项目并正在寻找一种方法来获取当前路线的孩子(使用打字稿)。无论 thethis.$route或 the 是否this.$router.currentRoute包含-prop children

有什么办法吗?

有了这些信息,我想存档以自动生成选项卡(子视图)。

更新 1

好的,获取子路由的解决方案如下:

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

现在的挑战是,来自子根的我首先需要得到父根。有没有办法让父母分别获得root-Route的孩子?

所以我需要当前或父/根路由的所有子级。

更新 2

好的,我目前想出了以下解决方案:

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

如果有任何更清洁/更好的解决方案,请告诉我。

标签: vue.jsvue-router

解决方案


按照我目前的解决方案:

<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>

与以下路由配置一起使用:

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

推荐阅读