我在 v-for 中为表行设置多种颜色时遇到问题。
我正在开发一个简单的足球应用程序,它将显示某个球队最近的比赛结果。
我的问题是:我想根据匹配结果更改元素的背景颜色:
- 获胜 -> 绿色
- 输了 -> 红色
- 绘制 -> 灰色
在我的页面上,我有一个调用“故事”功能的按钮。函数“story”只是将一支球队的所有比赛从“matches”数组推送到“history”数组中。完成此操作后,我检查球队是否获胜、失败或平局。然后我将“主题”变量更改为结果。
在我的 HTML 中,我现在将类动态设置为“主题”变量。
问题:所有表行现在都根据推送到“历史记录”数组中的最后结果设置为颜色。
我拼命寻找解决方案,但找不到我需要的东西。
这是我的代码:
<template>
<table id="table2">
<button class="button" @click="story"></button>
<tr :class="theme" v-for="match in history" :key="match">
<td>{{ match.team1 }}</td>
<td>{{ match.goals1 }}:{{ match.goals2 }}</td>
<td>{{ match.team2 }}</td>
</tr>
</table>
</template>
<script>
data() {
return {
matches: [
{
team1: Real Madrid,
team2: FC Barcelona,
goals1: 1,
goals2: 1
},
team1: Atletico Madrid,
team2: FC Barcelona,
goals1: 1,
goals2: 2
}
],
history: [],
theme: ""
}
},
methods: {
story: function() {
this.history = []; //empty past inserts
team = "FC Barcelona";
for (let i = 0; i < this.matches.length; i++) {
if (this.matches[i].team1 == team || this.matches[i].team2 == team) {
this.history.push(this.matches[i]); //paste match in history
//now I want to check if my team won, lost or had a draw
if (this.matches[i].team1 == team) {
if (this.matches[i].goals1 == this.matches[i].goals2)
theme = "draw";
else if (this.matches[i].goals1 < this.matches[i].goals2)
this.theme = "lose";
else if (this.matches[i].goals1 > this.matches[i].goals2)
theme = "win";
}
if (this.matches[i].team2 == team) {
if (this.matches[i].goals1 == this.matches[i].goals2)
theme = "draw";
else if (this.matches[i].goals1 > this.matches[i].goals2)
theme = "lose";
else if (this.matches[i].goals1 < this.matches[i].goals2)
theme = "win";
}
}
}
}
</script>
<style>
tr.lose {
background-color: rgb(202, 43, 43);
}
tr.win {
background-color: rgb(53, 86, 230);
}
tr.draw {
background-color: rgb(151, 151, 151);
}
</style>
最佳答案
您可以根据历史记录
创建计算属性并确定其中的主题。
...
data () {
return {
history: []
}
},
computed: {
themedHistory () {
this.history.map(item => {
// determine the theme based on the item
// const theme = ...
return {
...item,
theme
}
}
}
}
在你的模板中
<tr :class="match.theme" v-for="match in themedHistory" :key="match.id">
...
</tr>
关于javascript - Vue.js:v-for 中的表中有多个不同颜色的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59823555/