Home > front end >  How to add a class to specific elements created with a v-for loop?
How to add a class to specific elements created with a v-for loop?

Time:10-15

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!

CodePudding user response:

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

  • Related