Vue3模板中使用二维数组无法正常访问,求解决方法
Vue3二维数组遍历NFL分区排名失败问题排查与解决
问题场景
尝试在Vue3模板中通过二维数组展示NFL球队分区排名:通过computed属性筛选出AFC各分区的球队数据,将这些computed结果存入ref定义的afc数组;使用嵌套v-for遍历afc及其中的球队时,控制台报错,且内层team遍历无输出。
相关信息
Vue DevTools中的数组结构

模板代码
<template v-for="divsn in afc"> <!-- eslint-disable-next-line vue/require-v-for-key --> <div>{{ divsn }}</div> <!-- eslint-disable-next-line vue/require-v-for-key --> <table v-for="team in divsn"> <thead> <tr> /* Table Header Info */ <th>GB</th> </tr> </thead> <tbody> <tr> <th scope="row" colspan="2"> <img :src="team.team.logo" />{{ team.team.name }} </th> <td>{{ team.won }}</td> <td>{{ team.lost }}</td> <td v-if="team.ties">{{ team.ties }}</td> <td>{{ (parseInt(team.won + (.5 * (team.ties))) / (parseInt(team.won) + parseInt(team.lost + parseInt(team.ties))) * 100).toFixed(1) }}%</td> </tr> </tbody> </table> </template>
JS代码
// ============================================================================= // // =============== 按分区计算球队排名的Computed属性 ============== // // ============================================================================= // const afcEastStandings = computed(() => { return nflStandings.value.response.filter((team) => team.division === "AFC East"); }) /* 其他类似的computed属性(afcNorth/South/WestStandings) */ // ============================================================================= // // =============== 分区排名Computed属性定义结束 ======= // // ============================================================================= // const afc = ref([afcEastStandings, afcNorthStandings, afcSouthStandings, afcWestStandings]); ;
控制台报错

更新信息
打印divsn的结果如下,{{ team }}无输出:
问题根源
直接将computed创建的响应式对象存入ref数组,而computed返回的是RefImpl实例(并非直接的数组数据)。模板遍历divsn时,实际在遍历响应式对象的内部属性,而非预期的分区球队数组,导致内层遍历team无法获取有效数据,触发报错。
解决方案
方案1:保留响应式的最优写法(推荐)
将afc改为computed属性,返回由各分区computed值组成的数组,确保原数据变化时afc自动更新:
const afc = computed(() => [ afcEastStandings.value, afcNorthStandings.value, afcSouthStandings.value, afcWestStandings.value ]);
模板无需修改,Vue会自动在模板中解包computed返回的响应式数组。
方案2:直接存入数组值(无响应式)
若不需要响应式更新,可直接取每个computed的.value存入ref数组:
const afc = ref([ afcEastStandings.value, afcNorthStandings.value, afcSouthStandings.value, afcWestStandings.value ]);
注意:此方式下nflStandings变化时,afc数组不会同步更新。
额外优化:添加v-for的key属性
移除ESLint禁用注释,为v-for添加唯一key,符合Vue性能优化最佳实践:
<template v-for="(divsn, divIdx) in afc" :key="`afc-division-${divIdx}`"> <div>{{ divsn }}</div> <table v-for="(team, teamIdx) in divsn" :key="`afc-team-${team.team.id}-${teamIdx}`"> <!-- 表格内容保持不变 --> </table> </template>
内容的提问来源于stack exchange,提问作者Alan
相关产品推荐
相关产品推荐

