2

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?

1
  • should only one div be selected? or is select supposed to be toggling the state of the div? Commented Jun 8, 2022 at 0:34

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks you. This allow to select only one ligne of the array, not 2 or more at once. I guess I need to write a method for that.
@thiebo hey mate , check now please I updated my answer
works! Really cool

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.