vue.js - 从当前路线获取孩子
问题描述
我有一个 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
如果有任何更清洁/更好的解决方案,请告诉我。
解决方案
按照我目前的解决方案:
<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' }
}
]
},
推荐阅读
- angular - 在角度中使用发射输出属性优于 viewchild 的优势
- ruby-on-rails - 无法连接到 OpenTok。响应代码:创建会话时身份验证失败
- javascript - document.getElemetById 返回 TypeError: Cannot set property 'checked' of undefined
- python - 关于 Python 的 tfidf 和 word-cloud
- mongodb - 为 mongo-go-driver 动态创建聚合管道
- git - git不添加来自不同git目录的文件
- python - 如何在没有 SymPy 的情况下计算给定函数的积分?
- angular - 使用 Angular 7 Material CDK 进行嵌套拖放
- excel - 如何创建仅在选定单元格上运行的宏
- javascript - 调试打字稿