Search code examples
javascriptvue.jsv-for

Vue v-for expand only clicked data


I have a Vue project with Firebase. I am using v-for for getting data from Firebase database and I have a "description" value. When users click anywhere on tr I want to expand and show only clicked value's description. But in my code; when I click tbody expand all description values. How can I fix this?

My code:

<tbody v-for="item in items" :key="item.id" @click="isClicked = !isClicked">

        <tr >
          <td>
            {{item.name}} 
          </td>
          <td>
            {{item.surname}}
          </td>
          <td>
            {{item.explanation}}
          </td>
        <td>
          <span @click="isDelete(item)">X</span>
        </td>
        </tr>
        <tr v-if="isClicked === true">  
          {{item.desc}}
        </tr>
      </tbody>

Thank for helping.


Solution

  • Get the index of the loop:

    v-for="(item, index) in items"
    

    Make a function which accepts the index as an argument:

    setActiveRow(index)
    

    Assign the index to the isClicked variable:

    setActiveRow(index) {
      this.isClicked = index
    }
    

    Now use that as your click function and compare the isClicked variable in your row:

    <tbody v-for="(item, index) in items" :key="item.id" @click="setActiveRow(index)">
    

    And then only show the specific row if the index matches:

    <tr v-if="isClicked === index">
      <td> {{ item.desc }} </td>
    </tr>