Vue中如何正确编写v-for循环遍历多层嵌套数组
问题原因
你当前只遍历了外层的playerDataList.stats数组,对于每个stats元素下的内层splits数组,你直接硬取了下标[0]的元素,所以永远只能拿到每个stats下的第一条split数据。从你给出的示例数据来看,stats数组本身只有1个元素,所以最终只会渲染1条数据。
修正方案
分两种场景处理:
场景1:stats数组固定只有1个元素(你的示例数据属于这种情况)
直接遍历内层的splits数组即可,代码如下:
<div class="player-stats-card-inner"> <p class="close" @click='showPlayers = !showPlayers'>Close</p> <table> <thead> <tr> <th>赛季</th> <th>Goals</th> <th>Assists</th> <th>所属队伍</th> </tr> </thead> <tbody> <!-- 直接遍历splits数组 --> <tr v-for="(splitItem, index) in playerDataList.stats[0].splits" :key="`split-${index}-${splitItem.season}`" > <td>{{ splitItem.season }}</td> <td>{{ splitItem.stat.goals }}</td> <td>{{ splitItem.stat.assists }}</td> <td>{{ splitItem.team.name }}</td> </tr> </tbody> </table> </div>
场景2:stats数组可能包含多个统计分组
用template标签做外层容器嵌套循环即可,不会额外生成DOM节点,代码如下:
<div class="player-stats-card-inner"> <p class="close" @click='showPlayers = !showPlayers'>Close</p> <table> <thead> <tr> <th>统计类型</th> <th>赛季</th> <th>Goals</th> <th>Assists</th> </tr> </thead> <tbody> <!-- 外层遍历stats数组 --> <template v-for="(statsItem, statsIndex) in playerDataList.stats" :key="`stats-${statsIndex}`"> <!-- 内层遍历每个stats下的splits数组 --> <tr v-for="(splitItem, splitIndex) in statsItem.splits" :key="`${statsIndex}-${splitIndex}-${splitItem.season}`" > <td>{{ statsItem.type.displayName }}</td> <td>{{ splitItem.season }}</td> <td>{{ splitItem.stat.goals }}</td> <td>{{ splitItem.stat.assists }}</td> </tr> </template> </tbody> </table> </div>
补充注意点
- 原代码中
:key="stats.id"绑定的字段不存在,stats对象没有id属性,建议使用「下标+唯一业务字段(如赛季)」的组合作为key,避免渲染异常 - 原HTML表格结构不规范,th需要包裹在tr标签内,补充thead、tbody标签符合标准写法
- 多层数组遍历逻辑和原生JS一致,有几层数组就对应写几层v-for即可
内容的提问来源于stack exchange,提问作者user4759415
相关产品推荐
相关产品推荐

