Vue Router嵌套视图如何使用JSON格式router-link跳转?
用命名路由跳转Vue Router嵌套视图的正确姿势
嘿,这个问题我太懂了!你现在的需求是把字符串拼接的路径改成命名路由的JSON格式,其实只需要直接指定子路由的name,同时传入父路由所需的参数就行啦,不用复杂的配置。
具体修改方法
你原来的JSON写法只指定了父路由team的name,但要跳转到嵌套的players子路由,直接用子路由的name就可以了:
<router-link :to="{ name: 'players', params: { teamId: team.id_team } }">Players</router-link>
同理,跳转到staff或table子路由时,只需要把name换成对应的子路由名称:
<!-- 跳转到staff子路由 --> <router-link :to="{ name: 'staff', params: { teamId: team.id_team } }">Staff</router-link> <!-- 跳转到table子路由 --> <router-link :to="{ name: 'table', params: { teamId: team.id_team } }">Table</router-link>
为什么这样可行?
Vue Router会根据你配置的嵌套路由关系,自动关联父路由和子路由:
- 子路由
players属于父路由team,当你指定子路由的name时,Vue Router会自动匹配父路由的路径/club/:teamId,再拼接子路由的路径players,最终生成正确的完整路径。 - 你只需要确保传入父路由所需的
teamId参数,子路由会自动继承父路由的参数(如果需要的话)。
小优化:清理无效的路由配置
另外注意一下,你子路由里的params: true是无效的配置项哦,Vue Router的路由配置里没有这个属性,直接去掉就好,不影响功能:
{ path: '/club/:teamId', name:'team', component: team, children :[ { name:'players', path: 'players', component: teamPlayers }, { name:'staff', path: 'staff', component: teamStaff }, { name:'table', path: 'table', component: teamTable } ] }
这样修改后,既保持了命名路由的简洁性,又完美适配了嵌套视图的跳转需求,比手动拼接字符串路径更可靠也更易维护~
内容的提问来源于stack exchange,提问作者Uncoke
相关产品推荐
相关产品推荐

