Apply the class only if the v-for loop is rendering the current item

Apologies for my code, I am still learning Vue.

I have 5 span items set up like this [span with :class]

              <span class="bars">
                <span class="bar" :class="{ selected1: isActive[0] }"></span>
                <span class="bar" :class="{ selected2: isActive[1] }></span>
                <span class="bar" :class="{ selected3: isActive[2] }></span>
                <span class="bar" :class="{ selected4: isActive[3] }></span>
                <span class="bar" :class="{ selected5: isActive[4] }></span>
              </span>

These correspond to 5 grey circles. The classes 'selected1, selected2, ...' fill the circles with different colors. The "isActive" array consists of 5 boolean variables [false, false, false, false, false]. A function is used to update these boolean variables each time data is received from Firebase.

  data() {
    return {
      isActive: [], // boolean array
      ricettario: [] // firebase data array
    };
  },

So when isActive[0] is true, the first span is filled, and so on...

The function responsible for updating isActive[] is called "setDiff" which retrieves data from Firebase Database and processes it through a switch statement.

// Get data from Firebase
created() {
    db.collection("ricettarioFirebase")
      .get()
      .then(snapshot => {
        snapshot.forEach(doc => {
          let recipe = doc.data();
          recipe.date = dayjs(recipe.date)
            .locale("it") 
            .format("D MMMM YYYY");
          this.setDiff(recipe.diff); 
          this.ricettario.push(recipe); 
        });
      });
  }


// Function to update isActive[]
  methods: {
    setDiff(diff) {
      switch (diff) {
        case "molto facile":
          i = 1;
          for (j = 0; j < i; j++) {
            this.isActive[j] = true; 
          }
          break;
        case "facile":
          i = 2;
          for (j = 0; j < i; j++) {
            this.isActive[j] = true; 
          }
          break;
        case "medio":
          i = 3;
          for (j = 0; j < i; j++) {
            this.isActive[j] = true; 
          }
          break;
        case "difficile":
          i = 4;
          for (j = 0; j < i; j++) {
            this.isActive[j] = true; 
          }
          break;
        case "molto difficile":
          i = 5;
          for (j = 0; j < i; j++) {
            this.isActive[j] = true; 
          }
          break;
      }
    }
  }

The issue here is that the DOM only displays the last updated state, causing all cards created with v-for to have the same span color. The goal is to have each card with different filled spans. The problem can be seen in the following image. problem

Answer №1

There is a single global variable called isActive[]

An array of objects is being retrieved from the database.

Each object in the array has setDiff(someString) called on it, which overrides the values set by the previous call every time.

To address this issue, consider turning isActive into a two-dimensional array (e.g. isActive[item.id][0]) or attaching it to the "ricetta" object before pushing it into the "ricettario" array.

ricetta.isActive = this.setDiff(ricetta.diff); // don't forget to return isActive from the setDiff function
ricettario.push(ricetta)

In solving this problem, you might also leverage basic CSS and a :class based on ricetta.diff

https://codepen.io/szkuwa/pen/JjdNYov

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

Is there a way to incorporate multiple functions into a single sx property, such as color, zIndex, backgroundColor, etc? Can this be achieved in any way?

I am currently developing a single search component that will be used across various sections of my application. Each component receives a prop called search: string to determine its type and apply specific styles accordingly. Although I could use classNam ...

HTML code displaying a fixed message at the top of the webpage

I'm working on a web page that has a lot of content. I need to have a message always visible at the bottom of the browser window, even when scrolling. Can anyone help me achieve this using simple CSS, HTML, jQuery, or PHP? Thanks! ...

converting the names of files in a specific directory to a JavaScript array

Currently working on a local HTML document and trying to navigate through a folder, gathering all the file names and storing them in a JavaScript array Let's say I have a folder named Videos with files like: - VideoA.mp4 - VideoB.mp4 How can I cre ...

Clear existing markers from the map before inserting new markers

I have a map where initially the markers load coming from the database, Then there is a time-based Ajax request that fetches new records every minute. In my code snippet, I am using setMapOnAll(null) following the guidance from the Google Maps Documentati ...

Function in Typescript that can return multiple data types

I recently started learning about TypeScript and its concepts. During my practice sessions, I encountered a problem that left me puzzled. There is a function named `functionA` which returns an object based on the response received from an API. type Combina ...

Exploring the integration of Bootstrap Confirmation into an ASP.NET web page

I'm currently working on implementing Bootstrap Confirmation (http://ethaizone.github.io/Bootstrap-Confirmation/#top) on an ASP.NET web page using C#, but I've encountered some issues. Master Page References <asp:ScriptReference Path="Script ...

multer not working for file upload in Nuxt3

When using nuxt3/node.js with multer, I am facing an issue where I cannot store or receive a file on my server and the req.file appears to be empty all the time. Here is a snippet of my server code: const upload = multer({ dest: './uploads/' }) r ...

Having trouble modifying a value in a form and submitting it to the following jsp page

I'm encountering an issue with changing the value in a hidden input element before submitting data to another JSP file (db.jsp) for processing. The value should be different depending on which button is clicked, but it always remains as the default va ...

Upon loading the page, the menu automatically drops down for easy navigation

Currently, I am working on a WordPress site using the WallBase theme. You can check out a preview of the theme here. One issue I am facing is that when the page fully loads, the menu automatically drops down. I have tried various solutions to keep the me ...

Utilizing a TypeScript function to trigger an action from within a Chart.js option callback

Currently, I am utilizing a wrapper for Chart.js that enables an animation callback to signify when the chart has finished drawing. The chart options in my code are set up like this: public chartOptions: any = { animation: { duration: 2000, ...

Make sure a specific piece of code gets evaluated in a timely manner

To ensure the default timezone is set for all moment calls in the app's lifetime, I initially placed the setter in the entry point file. However, it turns out that this file is not the first to be evaluated. An issue arose with one of my reducers wher ...

What is the best way to enable a service to retrieve variables from the Controller?

My controller has variables declared on the $scope and two arrays that hold objects: one for available groups and the other for groups the user is already a part of. The addUserToGroups() function sends a call to the server to add the user to the selected ...

Jquery Issue: Safari Leaves Alert Messages Unclosed When Opening Next Alert

I am experiencing an issue in Safari Browser and need some help with the following scenarios (with Example). When I click a button to delete an account, an alert message pops up. This alert window has two actions - "OK" and "Cancel". If I click "OK", it r ...

Leveraging Server Response Codes Across Different Domains Using JavaScript

Before anything else, I must acknowledge the cross-domain issues that may arise with JavaScript. The fact that I am seeing both 404 and 200 response codes in my console has made me reconsider this possibility. The scenario... I am currently developing a w ...

How to dynamically add a form to your website

Looking to dynamically insert a form on a page based on the value selected from a datalist, all without having to reload the entire page. <form action='#' method='get'> <input list="category" name="category"> <da ...

When should the preloader be placed within the DOMContentLoaded or load event?

I'm looking to implement a preloader on my website to ensure everything is fully loaded - images, JavaScript, fonts, etc. However, I'm unsure whether to use the following: window.addEventListener('DOMContentLoaded', () => { // code ...

Failed installation of Semantic-ui through npm encountered

Encountering an error while attempting to install semantic-ui through npm for a new project. Here are the version details: $ node -v v16.14.0 $ npm -v 8.10.0 $ npm i semantic-ui npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Unexpected fragments returned by Woocommerce during woocommerce_add_to_cart_fragments hook

I'm currently working on a unique customization for my WooCommerce cart where I am trying to update the quantity of a cart item dynamically. Although the updating functionality works correctly, I'm facing an issue where the cart doesn't refr ...

Creating a NURBS surface in Three.js using an NxN grid of control points

Yesterday, I attempted to plot a 3D Math function [ F(x,y) ] by calculating various points (x, y, z) in space and representing them as white points. Here is an example: https://i.sstatic.net/4kM4x.png Inital Issue: When I adjusted the scenario using Orbi ...

The functionality of the Protractor right click feature is smooth, however, there seems to be an issue with selecting

https://i.sstatic.net/KoGto.png Even though I can locate the button within the context menu, I am facing difficulty in clicking it. The code mentioned below is successfully able to click the button, but an error message pops up indicating: Failed: script ...