Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

292
Views
Vuejs : how to bind class within a v-for loop

In Vuejs3, I'm looping over an array of objects :

<div 
   v-for="ligne in lignes" 
   :key="ligne.id" 
   :class="{ 'border-b-2':isSelected }" 
   :id="`ligne_${ligne.id}`"
 >
     <span @click="select(ligne.id)">X</span>
</div>

I want to add the class 'border-b-2' only to the line selected line, but I don't see how to do that dynamically. When I now set isSelected to true in the vue devtools, all lines get that style applied.

As a workaround, what I now do is wrapping this code in a function (select(id)) and change the html class

document.getElementById(`ligne_${id}`).classList.add('border-b-2')

That seems verbose. How to do this, leveraging on the :key or the v-for loop?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Try to set id in isSelected instead of boolean:

const app = Vue.createApp({
  data() {
    return {
      lignes: [{id: 1}, {id: 2}, {id: 3}],
      isSelected: [],
    }
  },
  methods: {
    select(id) {
      if(this.isSelected.includes(id)) {
        this.isSelected = this.isSelected.filter(s => s !== id )
      } else this.isSelected.push(id)
    }
  }
})
app.mount('#demo')
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" integrity="sha512-wnea99uKIC3TJF7v4eKk4Y+lMz2Mklv18+r4na2Gn1abDRPPOeef95xTzdwGD9e6zXJBteMIhZ1+68QC5byJZw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="ligne in lignes" :key="ligne.id" 
    :class="isSelected.includes(ligne.id) && 'border-b-2'"
  >
    <span @click="select(ligne.id)">X</span>
  </div>
</div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!