Reputation: 91
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.
Upvotes: 0
Views: 1468
Reputation: 50798
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>
Upvotes: 1
Reputation: 2384
First you need to understand what actually your code is doing, you are listening to click at tbody, and on click of that you are setting the flag isClicked as true/false, and all your items are v-if(ed) at single flag i.e., isClicked. So whenever the flag changes every v-if will also react, that is why every description is shown, which definitely is not desired.
Listening to click on tbody is wrong you should listen to click at every tr-s, so that you can actually know which tr is clicked. Now on click of any tr, store the id of that tr and display the description of the respective item.
Well there is a small work around you can actually do in your code to make it work as you wanted.
Here is the modified code.
<tbody v-for="item in items" :key="item.id">
<tr @click="isClicked = item.id">
<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 === item.id">
{{item.desc}}
</tr>
</tbody>
I hope it helps.
Upvotes: 0