I'm struggling to apply different colors to my table rows in a v-for loop.
Currently, I'm developing a basic soccer app that displays recent match outcomes for a specific team.
The issue I'm facing is related to changing the background color of each row based on the match result:
- win -> green
- lose -> red
- draw -> grey
On the web page, there's a button that triggers the "story" function. This function essentially adds all matches of a team from the "matches" array into the "history" array. After this process, the code checks if the team won, lost, or drew the match. Subsequently, it updates the "theme" variable accordingly.
In the HTML section, the class attribute is dynamically set based on the "theme" variable.
However, the problem arises when all table rows are displaying the color corresponding to the last result added to the "history" array.
Despite multiple attempts to find a solution, I haven't been able to resolve this issue.
Below is the code snippet:
<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 = []; //clearing previous records
const 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]); //adding match to history
//checking whether 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>