Skip to content
Advertisement

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?

Advertisement

Answer

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>
Advertisement