Expand only the clicked data in Vue v-for loop

I've come across a challenge in my Vue project with Firebase. I'm using v-for to fetch data from the Firebase database, and each item has a "description" value. I want to be able to expand and show only the description of the clicked item when users click anywhere on the table row (tr). However, the issue is that when I click on the tbody, all description values expand. How can I resolve this?

Here's my current 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 you for any assistance provided.

Answer №1

Retrieve the position of the loop:

v-for="(element, position) in elements"

Create a function that takes the position as a parameter:

selectActiveElement(position)

Set the position value to the isSelected variable:

selectActiveElement(position) {
  this.isSelected = position
}

Now use this as your click action and compare the isSelected variable in your row:

<tbody v-for="(element, position) in elements" :key="element.id" @click="selectActiveElement(position)">

Show only the specific row if the position matches:

<tr v-if="isSelected === position">
  <td> {{ element.description }} </td>
</tr>

Answer №2

To effectively address the issue in your code, it is crucial to grasp its functionality. Currently, you have a setup where clicks on the tbody element toggle the flag isClicked between true and false. This flag controls the visibility of all items using v-if directives. Consequently, any change in the flag triggers a reevaluation of all descriptions, leading to undesired outcomes.

The approach of listening for clicks on the entire tbody is flawed. Instead, consider capturing clicks on individual tr elements to determine which specific row is clicked. By storing the id of the clicked row, you can then display the corresponding item's description.

However, there is a workaround that can align your code with the desired behavior. Here is the revised implementation:

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

Implementing these changes should help achieve the intended functionality. Best of luck!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging JSON for fetching distinct identifiers from a database

When a user hovers over a parent span containing an empty img tag, I use JSON and jQuery to retrieve the src of the image from the database. The issue arises when the retrieved src is applied to all looped span images on the same page, instead of each imag ...

Select the array using the .shift method

I have a deck of shuffled cards represented as an array. Currently, I am manually picking 2-5 cards from the 'myDeck' array and displaying them. Is there a better way to do this using a loop? At the moment, I am using individual variables like: ...

Increase the value of a number using jQuery

When using jquery to animate a random number increment from 0001 to 1000, the issue arises when reaching the number 0077. The final number displayed is 77 instead of 0077. Is there a solution to ensure the format remains as 0077? Your help is appreciated. ...

Error with shader in webgl/three.js

i'm struggling with some issues in three js and need help with parallax mapping. vertex shader : varying vec3 v_pos; varying vec3 v_nrm; varying vec2 v_txc; void main(){ v_pos = position; v_nrm = normal; v_txc = uv; gl_Positi ...

How can AngularJS be used to automatically check a checkbox based on a value in one array, and simultaneously update another array with the checked value or remove it if

enter image description hereHere is a brief overview of the HTML code: I aim to display options from an array within a set object while ensuring that checkboxes are checked for the answers present in another answer array. Furthermore, new answers should be ...

Having trouble with Bootstrap 4 maintaining consistent width when affixing the sidebar

Hello there, I'm currently working with Bootstrap 4 and trying to implement affix on the sidebar. I have set up three columns for the sidebar and made them fixed under certain conditions. However, I am facing an issue where the width of the sidebar ch ...

How to build a flexible gridlist in VUEJs

I've recently become intrigued by VueJs and am on the lookout for a straightforward method to create a dynamic gridlist in VUEJs featuring firstName, lastName, and images for each person. Here's what I attempted, and here's how it turned ou ...

Access the value of a variable passed from the view to the controller

Is there a way to retrieve a dynamically generated value from the view to the controller in AngularJS? <ng-option ng-repeat="w in details track by $index"> <div class="program-grid-row table-row" > <div> <a class= ...

What is preventing the installation of bootstrap-vue on my system?

I'm facing an issue while attempting to set up bootstrap-vue in my vue project. I used the command npm install bootstrap-vue bootstrap, but encountered a perplexing error message. npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class=" ...

Encountered Vue-Router issue: "SyntaxError: Unexpected token" while building module

I encountered an error while trying to compile this VueJS demo project. Despite updating NPM and the app's dependencies to the latest stable versions, the error persists. The error disappears when I remove vue-router from both index.js and main.js. T ...

Issues with displaying markers on Google Maps API using JSON and AJAX

I have successfully coded the section where I retrieve JSON markers and loop through them. However, despite this, the markers do not seem to be appearing on the map. Could someone please assist me in identifying the mistake? $.ajax({ url ...

What is the proper way to transfer data from a file using npm's request package?

I'm currently utilizing npm's request module to interact with an API. The API specifications require that data be sent through a file using the @site.json notation when making a CURL request. For example: curl -X POST -d @site.json 'https ...

Challenge with decrypting data using Mysql's AES_ENCRYPT and client-side Javascript Aes.Ctr.decrypt

The issue at hand I have confidential data stored in a MySQL database, and I am looking to encrypt this data when performing a SELECT query. Subsequently, I aim to decrypt it on the client-side using JavaScript. Here is an example: MySQL SELECT query: ...

Unable to display Apexcharts bar chart in Vue.js application

Struggling to incorporate Apexcharts into my Vue.js site, but unfortunately, the chart isn't appearing as expected. -For more guidance on Apexcharts, check out their documentation Here HTML <div class="section sec2"> <div id="chart" ...

Vue doesn't seem to be compatible with arrays

https://i.sstatic.net/skdsH.png The current code is functioning perfectly. However, if any modifications are made to the code, it fails to work as intended. https://i.sstatic.net/dO2Hp.png If anyone out there has expertise in Vue.js, I would greatly app ...

Managing an unexpected variable when making an AJAX request

Here is a code snippet that I am working with: var User = { get: function (options) { var self = this; $.ajax({ url: options.url, success: function (data, response) { self.nextPageUrl = data.pagination.next_page; opt ...

Utilizing $index in AngularJS while iterating through ng-repeat items

Here is an example of an unordered list: <ul class="dropdown-menu inner" role="menu"> <li ng-repeat="availableAlphaName in availableAlphaNames" data-original-index="0" data-optgroup="1" class=""> <a tabindex="0" class="opt " st ...

Steps to trigger an alert when the entered quantity exceeds the current stock levels

After developing an IMS System, I encountered a problem where my stock is going into negative figures. To resolve this issue, my primary goal is to trigger an alert whenever the quantity entered by a user exceeds the available stock. For example, if a us ...

Different ways to split up information on the client side into separate "pages"

Looking for a way to split a lengthy HTML text-only article into multiple divs for easier page navigation on mobile devices? Perhaps dividing it into separate pages that users can swipe through on their iPad or iPhone? I've experimented with JavaScri ...

Adjust the size of each link in the highchart network diagram

Is it feasible to individually set the length of each link in a network graph using highcharts? I am interested in creating a visualization where each user is displayed at varying distances from the main center user. I have been experimenting with the lin ...