You need to enable JavaScript to run this app. Vue使用v-for从无序赛事数组提取主客场队名渲染的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

Vue使用v-for从无序赛事数组提取主客场队名渲染的实现方法

实现方案

方案1:直接在模板中查找(适合数据量较小的场景)

直接通过Array.find()方法按type匹配对应队伍,无需在意数组顺序:

<template>
  <div>
    <!-- 遍历赛事列表 -->
    <div v-for="(match, index) in matchData" :key="index">
      <strong>{{ (match.options.find(item => item.type === 'home') || {}).teamname }}</strong>
      vs
      <strong>{{ (match.options.find(item => item.type === 'away') || {}).teamname }}</strong>
    </div>
  </div>
</template>

注:上面的|| {}是Vue2兼容写法,避免未匹配到对应type时报错,如果是Vue3项目可以直接用可选链写法:match.options.find(item => item.type === 'home')?.teamname

方案2:计算属性预处理(推荐,性能更优)

把数据处理逻辑放到计算属性中,模板只负责渲染,逻辑更清晰,重复渲染时性能更好:

<script>
export default {
  data() {
    return {
      // 接口返回的原始赛事数据
      matchData: [
        {
          "options": [
            { "type": "home", "teamname": "xxx" },
            { "type": "away", "teamname": "yyy" },
            { "type": "draw", "teamname": "no winner" }
          ]
        },
        // 剩余数据项
      ]
    }
  },
  computed: {
    processedMatchList() {
      return this.matchData.map(match => {
        // 提前匹配好主客队
        const homeTeam = match.options.find(item => item.type === 'home')?.teamname || ''
        const awayTeam = match.options.find(item => item.type === 'away')?.teamname || ''
        return { homeTeam, awayTeam }
      })
    }
  }
}
</script>

<template>
  <div>
    <div v-for="(match, index) in processedMatchList" :key="index">
      <strong>{{ match.homeTeam }}</strong> vs <strong>{{ match.awayTeam }}</strong>
    </div>
  </div>
</template>

内容的提问来源于stack exchange,提问作者Mr.K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 20:45:03