You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue路由:共享组件中如何跳转当前父路由的同名子路由?

动态跳转到当前父路由的new子路由(非硬编码实现)

你的场景是多个父路由(如FeatureA、FeatureB)都包含路径相同的子路由,共享组件需要生成跳转到当前父路由下new子路由的链接,避免硬编码父路由路径。以下是两种可靠的实现方式:

方案一:通过路由名称推导(最健壮)

你的路由命名有固定规律:Grid页路由名称为featureX-grid,对应New页为featureX-new。利用这个规律,从当前路由名称直接推导目标路由名称:

Vue 3 组合式API

<template>
  <a :href="$router.resolve({ name: currentNewRouteName }).path">
    新建
  </a>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()

// 替换路由名称的后缀,得到对应new页的路由名
const currentNewRouteName = route.name.replace('-grid', '-new')
</script>

Vue 2 选项式API

<template>
  <a :href="$router.resolve({ name: currentNewRouteName }).path">
    新建
  </a>
</template>

<script>
export default {
  computed: {
    currentNewRouteName() {
      return this.$route.name.replace('-grid', '-new')
    }
  }
}
</script>

这种方式不依赖路由路径,即使后续修改父路由的path(比如把featureB改成featureC),组件代码也不需要调整。

方案二:使用相对路径(最简洁)

Vue Router支持相对路径解析,直接基于当前路由位置生成目标路径:

用原生a标签

<template>
  <!-- ./new 表示当前路由的同级子路由 -->
  <a :href="$router.resolve('./new').path">新建</a>
</template>
<template>
  <router-link to="./new">新建</router-link>
</template>

这种方式会自动根据当前所在的父路由(比如/featureB)生成/featureB/new的链接,完全不需要硬编码父路由信息。


内容的提问来源于stack exchange,提问作者juliano.net

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:20:24