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
相关产品推荐
相关产品推荐

