Display items within a v-for loop: VueJS

I am facing an issue with my v-for loop which displays all the items along with a panel for each item that allows modification and deletion. However, when I click on these buttons to display the panel or modify an item, it affects all of the items instead of just one. How can I fix this so that it only applies to the specific item I clicked on?

Here is the code snippet:

<div v-for="(comment, index) in comments" :list="index" :key="comment">
   <div v-on:click="show = !show">
      <div v-if="show">
         <button @click="edit(comment), active = !active, inactive = !inactive">
            Modify
         </button>
         <button @click="deleteComment(comment)">
            Delete
         </button>
      </div>
   </div>
   <div>
      <p :class="{ active: active }">
        {{ comment.content }}
      </p>
      <input :class="{ inactive: inactive }" type="text" v-model="comment.content" @keyup.enter="doneEdit">
   </div>
</div>

And here are the methods and data being used:

data() {
  return {
    show: false,
    editing: null,
    active: true,
    inactive: true
  }
},

methods: {
   edit(comment) {
     this.editing = comment
     this.oldComment = comment.content
   },

   doneEdit() {
     this.editing = null
     this.active = true
     this.inactive = true
   }
}

Answer №1

All items have the same states - show, editing, active, inactive. Changing data for one item affects all items. There are numerous ways to achieve your desired outcome.

An easy solution is to manage your data by index. For example:

<div v-on:click="showIndex = index">
  <div v-if="showIndex === index">
  ...
data () {
  return {
    showIndex: null
  ...

The downside of this method is that you can only work with one item at a time. If you require more complex functionality and want to handle multiple items simultaneously, I recommend creating separate components for each item with its own state (show, editing, etc.)

Answer №2

If you're looking to have multiple elements open at the same time, @NaN's solution may not work for you as it only allows one element to be open at a time. In order to achieve the ability to have several elements open simultaneously, you'll need to track each individual element separately rather than just relying on the boolean value of show.

Here's what you should do:

Firstly, change show from a boolean to an array:

data() {
  return {
    show: [],
    editing: null,
    active: true,
    inactive: true,

  }
},

This will enable you to keep track of which elements should display their panel:

<div v-on:click="toggleActive(index)">

Implement the following method:

methods: {
   toggleActive(index) {
      if (this.show.includes(index)) {
        this.show = this.show.filter(entry => entry !== index);

        return; 
      }

      this.show.push(index);
   }
}

Lastly, update your v-if condition like so:

<div v-if="show.includes(index)">

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

Creating a course specialized in numerical concepts

I have a routine where I assign classes to paragraphs based on their content: $("p").each(function(i, elem) { typeof elem === "number" ? ($("p").addClass("number")) : ($("p").addClass("other")) }) .number { color: blue; } .other { color: ...

Firebase Database Integration with AngularJS: Loading Results Dynamically upon Button Click or Action

Even though I can successfully retrieve data from my Firebase database, the scopes in my AngularJS application aren't updating automatically. It seems like the issue lies within AngularJS, but I'm unable to pinpoint the exact cause. Below is the ...

How to utilize JavaScript to convert a string into a function name

In this specific scenario, I am required to trigger a function based on the data attributes associated with an HTML element. function func1(arg1){ alert("func1"); } function func2(arg2){ alert("func2"); } jQuery(document).on('click', & ...

Utilizing HTML and JavaScript to add grayscale effect to images within a table, with the ability to revert to the colored version upon mouseover

Seeking advice on utilizing the mouseover / mouseout event in javascript to implement grayscale on a table. The challenge requires creating a gray image grid (table) using HTML and then incorporating Javascript so that hovering over an image triggers it to ...

I would appreciate your assistance in understanding how to utilize the Array concat() method in my code, and I am

I need help understanding how to use the Array concat() method and how to write pure JavaScript code according to the ECMA-262 standard. Assume O is the object we are working with. Let A be the new array created based on O with a length of 0. Set the ini ...

Utilizing the power of Datatables through AJAX calls with HTML Forms

Hello, I am currently working on incorporating djangorestframework-datatables with the datatables' JQuery plugin. My task involves loading a large table (consisting of approximately 15000 entries, paginated) with the serverSide option enabled. Enabli ...

Use JavaScript to enclose elements that are siblings within a DIV

Can you help me convert the elements with class "a" into a div using JavaScript, while maintaining their order within their sibling elements? I've been struggling with the code below and would appreciate any assistance. const elementParent= documen ...

communication flow in two directions between server and client

Looking for recommendations on a javascript/nodejs solution that enables bi-directional communication between server and client. The application flow involves the client sending a discovery service to the server, which responds with a challenge. The client ...

Using an object as a parameter in a NodeJS function

This past week, I encountered a challenge that has been difficult to overcome. I've been attempting to pass a JSON object as a parameter in a function, but I keep receiving an error message stating that it's not possible. Unfortunately, I don&apo ...

React-querybuilder experiencing issues with validator functionality

While utilizing the react-querybuilder, I have encountered an issue with field validation not functioning correctly. Upon reviewing this StackBlitz, it appears that when clicking on Rule and checking all fields, there are no errors present. export const fi ...

jQuery color picker plug-in for selecting and displaying a range of colors

I am currently developing a program that utilizes HTML, CSS, JavaScript, and JQuery for its user interface. One essential feature of this UI is the ability for users to choose one option from a set list of colors. It is crucial that each element in this co ...

The switch switches on yet another switch

Greetings everyone, Currently, I am in the midst of my exam project and creating a mobile menu. The functionality is there, but unfortunately, when closing the menu, it also triggers the search toggle which displays an unwanted div, becoming quite botherso ...

The application of textures is not being done correctly

Trying to incorporate two textures - one for the wall and another for the floor. However, after rendering, only a solid color is displayed instead of the desired texture. Below is the configuration of my scene and camera: const tempScene = new THREE.Sc ...

How can I ensure that Bootstrap Navbar elements are all aligned in a single line?

https://i.sstatic.net/pkxyI.pngI'm experiencing an issue with my code, and I suspect it might be related to Bootstrap. I've tried using align-items-center but it doesn't seem to work as expected. Changing the display property to inline or in ...

How to Use Django to Load a Text File into an HTML File with the Help of

I came across an interesting code example on a website called w3schools.com that I would like to incorporate into my Django project. The code utilizes the jquery load() function to load a text file into an HTML file. Here is a snippet of the code: <!DOC ...

Displaying the appropriate DIV element based on the value entered by the user

I am encountering some difficulties... I have an <input> field. Depending on the input, one of the various <div> elements should be displayed. For now, it's just a text (e.g. "Your plan contains less than 1500 kcal!"), but later, the div ...

Is it possible to pre-select a value in a PrimeVue Dropdown component?

Situation: Currently, I am incorporating PrimeVue into a Vue.js project. Within this setup, there is a dropdown component sourced from PrimeVue, utilizing an array of objects. The structure of the dropdown component appears as follows: <template #positi ...

Parenting and Child Components: Keeping the State in Sync

I am currently diving into my initial React project which focuses on a basic expense tracker for credit cards. While I'm still in the learning phase, I hope you can decipher the intent behind my code. My current roadblock involves mapping the state an ...

Angular - Utilizing Mat Paginator with Multiple Tables within a Single Component

I've been struggling with an issue for quite some time now, trying to find a solution but nothing seems to be working. Currently, I am facing an obstacle while rendering five tables on the screen. The data for these tables is fetched using a GET call ...

Troubleshooting problem with background URL path in Vue CLI Webpack

When using vue cli, I've encountered an issue with some of my images in relation to relative paths. If I refer to them directly in the scss without binding them dynamically to my vue object, there are issues. For example, if I have a div called "box" ...