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

Vue Router嵌套路由编程式导航跳转路径错误求助

解决Vue嵌套路由编程式导航跳转错误的问题

我一眼就瞅出问题所在啦——你的子路由路径配置犯了个常见的小错误!

问题根源:绝对路径导致路由不嵌套

Vue路由规则里,子路由的path如果以/开头,会被解析为根路径下的绝对路由,而不是相对于父路由的嵌套路径。你现在的子路由path: '/match/:matchId'就是绝对路径,所以调用$router.push时,它直接跳转到了根路径下的/match/:matchId,而不是你期望的/summoner/:summonerName/match/:matchId。

修复步骤

1. 修改子路由的路径配置

把子路由的path开头的斜杠去掉,改成相对路径:

{ 
  path: '/summoner/:summonerName', 
  component: Summoner, 
  children: [ 
    { path: '', component: Matchlist }, 
    // 去掉开头的/,变成相对父路由的路径
    { path: 'match/:matchId', component: SpecificMatch, name: 'specificMatch' } 
  ] 
}

2. 清理$router.push里的冗余参数

你在params里传递了summonerInfo和match,但这两个并不是路由定义中声明的参数——路由只需要summonerName和matchId。非路由参数塞到params里不仅没用,还可能干扰路由解析。

如果需要传递额外的非路由数据,推荐这几种方式:

  • 用query参数(会拼在URL后面,适合简单数据):
    this.$router.push({ 
      name: 'specificMatch', 
      params: { 
        summonerName: this.summoner, 
        matchId: matchId
      },
      query: {
        // 如果是对象,记得序列化,比如JSON.stringify(this.summonerInfo)
        summonerInfo: JSON.stringify(this.summonerInfo),
        match: JSON.stringify(match)
      }
    })
    
    接收的时候用this.$route.query,再解析成对象:JSON.parse(this.$route.query.summonerInfo)
  • 如果是父子组件(Summoner和SpecificMatch),可以通过父组件的<router-view>传递props
  • 用Vuex存储全局状态(适合复杂或跨组件的数据)

3. 确认父组件包含<router-view>

虽然你说直接访问嵌套路径时正常,但还是要确认Summoner组件里有没有<router-view>标签——这是渲染子组件的必要容器,没有它子路由组件根本显示不出来。

测试验证

修改完路由配置和push代码后,再调用this.$router.push,应该就能正确跳转到/summoner/:summonerName/match/:matchId路径了,SpecificMatch组件也能通过this.$route.params.summonerName拿到用户名参数啦。

内容的提问来源于stack exchange,提问作者Onyx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:03:27