Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

290
Visualizações
How to add a class to specific elements created with a v-for loop?

I am creating a simple inventory "checker" which basically creates 14 divs that are either "active" or "inactive". With vue I create these divs with a simple v-for loop:

<div class="inventory">
 <div class="item" v-for="index in 14" :key="index" ></div>
</div>

Where I'm stuck is that I receive data from another source that provides me an array with numbers of the inventory items that are considered "active".

for example:

[{"id": "5","date": "2021-10-08 11:30:55"},{"id": "4","date": "2021-10-08 11:30:54"}]

Note: the date tag is irrelevant for my question but it gives an idea how the object is looking for me. there is more data in it that is irrelevant for my question

In this case that would mean I should give an "active" class to the 4th and 5th item in my inventory. I don't see how I can loop through the (v-for looped) items to essentially add a if(inventoryId == id){addclass 'active'} to it. Any tips or nice vue tricks I could apply here? If anything is unclear please let me know!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can change the array from other source to be an array containing number of id, maybe something like this:

let otherSource = [{"id": "5","date": "2021-10-08 11:30:55"},{"id": "4","date": "2021-10-08 11:30:54"}]
// activeIds as a state/data
this.activeIds = otherSource.map(el => Number(el.id))
// activeIds as computed property
activeIds(){
   return otherSource.map(el => Number(el.id))
}

you can put activeIds as a state / computed property

and then

<div class="inventory">
  <div class="item" v-for="index in 14" :class="activeIds.includes(index) ? 'active' : 'inactive'" :key="index" ></div>
</div>

You can also put this part as computed property for better

activeIds.includes(index) ? 'active' : 'inactive'

I think this will do

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda