Using Vue.js to create a table with dynamically colored rows in a v-for loop


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>

Answer №1

To dynamically assign themes to items in a history array, you can create a computed property that maps through the history array and determines the theme for each item.

...

data () {
    return {
        history: []
    }
},
computed: {
    themedHistory () {
        this.history.map(item => {
            // determine the theme based on the item
            // const theme = ...

            return {
               ...item,
               theme
            }
        }
    }
}

In your template, utilize the themedHistory array to apply the corresponding theme to each item.

<tr :class="match.theme" v-for="match in themedHistory" :key="match.id">
    ...
</tr>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

It is important for me to retain the values inputted by the user even when the webpage is refreshed

My form entry web page saves data to a local database via another file called "info1.php" after the submit button is clicked. This file also validates the entered data, such as email addresses, and refreshes the page to the home site if the data is invalid ...

Assign the value to the index of the dropdown list

Recently, I encountered a dilemma with my dropdown list. <label for="staffType">Staff Type<br /></label> <select id="myList" name="staffType" onchange="show()"> <option>Care Staff</option> <o ...

Creating a disappearing carousel on mobile and tablet that disappears when extended to md size

Currently, I am developing a website that consists of a .row with 3 columns at full size, each containing a bootstrap4 card. However, when the website is viewed on tablet or mobile devices, those 3 images should transform into a carousel display. I'm ...

Securing AJAX Requests: Encrypting GET and POST Requests in JavaScipt using Node.js

Looking for a way to secure ajax post and get requests using JavaScript. The process would involve: Server generates private and public key upon request Server sends the public key to client Client encrypts data with public key Server decrypts data wit ...

Error: Attempted to access undefined property 'renderMenu' in a promise without handling it

I am looking to generate a dynamic menu based on the JSON data provided below: [ { "teamId": "10000", "teamName": "Laughing Heroes", "superTeamId": "", "createTime": "2017-06-25T06:07:45.000Z", "createUserId": null }, { "team ...

Which Angular component, directive, or pipe would be best suited for creating dynamic HTML content similar to this?

(I am transitioning from React to Angular, so please bear with me if my question has a hint of React influence.) I am in need of developing an Angular component that can accept a string along with a list of terms within that string for displaying tooltips ...

Is it possible to update the state of an array within a .then() function in React?

` After retrieving an array of points with city and state information, I attempted to convert these points to latitude and longitude by making a fetch call. However, upon trying to update the state of the newly generated array, I found that it remained ...

Simulating nodemailer functionality for testing purposes using Jest

I recently implemented an endpoint for users to reset their passwords. Everything was working smoothly and my tests were passing without any issues until I integrated nodemailer to send password reset emails. For testing, I am using Jest. Oddly enough, w ...

Struggling to make an AJAX form function properly

I'm running into an issue while setting up a basic AJAX form. My goal is to have a message display on the same page upon successful login using a PHP form through AJAX, but currently, I get redirected to the PHP file after form submission. Can anyone ...

Encountering an issue with an AngularJS form containing ng-repeat when attempting to submit

Here is my form structure: two text inputs followed by an ng-repeat with a text input and radio button inside. <form class="form-horizontal" id="myForm" name="myForm"> <div class="form-group"> <label for="name" class="co ...

Alter the functionality of the input element that has a tag of 'multiple'

I am encountering an issue with a form that allows users to upload multiple photos. When selecting multiple files at once, everything works as expected. However, if a user wants to add images one by one, each new addition deletes the previous file due to t ...

A full-width div containing a child span is unable to be aligned to the right

After reviewing this fiddle, I'm struggling to get my menu aligned correctly at the right edge of the overall "card". Despite trying various methods like margins, right: 0, and float, nothing seems to work as expected. In some cases, I even end up los ...

What's the reason that app.use(app.static(...)); isn't functioning properly?

As someone who is new to programming, I am currently exploring Javascript, node.js, and express. I came across a question regarding the usage of app.use(express.static(path.join(...))); versus app.use(app.static(path.join(...)));. const app = express(); co ...

String creation from HTMLDivElement

Is it possible to create a string from a JavaScript HTMLElement Object? Here's an example: var day = document.createElement("div"); day.className = "day"; day.textContent = "Random Text"; If we have created the day HTMLDivElement Object, can we make ...

Combining two JSON objects in JavaScript is simple when their IDs correspond to each other in both objects

I have a query related to merging two different objects from the database, both in JSON format. These two objects share two key/value pairs: IRBId = ... and id = ..., which can be seen in the examples below: OBJ 1 { "data":{ "IRBs":{ "n ...

I'm having trouble with accessing an object by index in a knockout observablearray. It seems like the binding process is encountering difficulties

I'm completely new to stackoverflow and knockout, and I have a query. I want to access a JSON object by index. It works fine when I insert dummy data in my code, but it throws an error when I try to add data from JSON. Error Uncaught TypeError: Unab ...

issue with web worker not sending data to react component

I have incorporated the audio-recorder-polyfill into my React project to enable audio recording for Safari. While the recording seems to initiate successfully, there is an issue with the availability of audio data. The "dataavailable" event does not trig ...

Cannot assign type void to 'Intrinsic Attributes & Dispatch<SetStateAction<>>'

Just starting out with typescript and ran into this error: Error :Type '{ setTasks: void; }' is not assignable to type 'IntrinsicAttributes & Dispatch<SetStateAction<IStudy[]>>'. Property 'setTasks' does not e ...

Tips for minimizing Angular $digest-cycle invocations

Issue In my application, I have noticed that some callbacks are being called excessively during the $digest cycle. This high frequency of calls is causing performance concerns as these callbacks are triggered way more times than expected, sometimes even e ...

Show schedule in an HTML chart

I'm currently working with a table that displays the current status of a request. An example of how the table looks in HTML is shown below: https://i.sstatic.net/daDHy.png The table itself is quite simple, but I am having trouble figuring out how to ...