How to make changes to the state in Vue.js while using v-for loop

Currently, I am retrieving comments from an API and attempting to modify a specific comment from the list.

Upon clicking the edit button, a text area appears within the comment box along with a save button, functioning as expected.

The issue arises when clicking the edit button, as the edit text area is applied to all comment boxes instead of just the selected one.

         <div>
                    <i class="fas fa-pen text-action text-success mr-3" @click="showComment(comment.id)" v-if="user == comment.user_id" v-b-tooltip.hover title="edit"></i>
                    <i class="fas fa-times-circle text-danger" v-b-tooltip.hover title="delete" v-if="!editing" v-show="user == comment.user_id"></i>
                    <i class="fa fa-times text-action text-danger mr-3" v-if="editing" @click="editing = false" v-b-tooltip.hover title="cancel editing"></i>
                </div>
            </div>
            <div v-if="editing">
                <textarea class="form-control" v-model="commentEdited" :id="comment.id" :placeholder="comment.body"></textarea>
                <button class="btn btn-xs btn-success" @click="editComment(comment)">save</button>
            </div>


The showComment method:

showComment(comment_id) {
    console.log("clicked" + comment_id);
    for (let i = 0; i < this.comments.length; i++) {
        if (this.comments[i].id == comment_id) {
            this.comment.body = this.comments[i].body;
            this.comment.id = this.comments[i].id;
            this.editing = true;
        }
    }
},

The editing boolean variable controls the editing state.

It's essential that upon clicking edit, only the textarea for the current comment opens, not all comments. I'm struggling to find a solution to this problem. Any assistance would be greatly appreciated.

Answer №1

One reason for this behavior is that the editing boolean is utilized by all components, causing all comments to display when it is set to true. An alternative approach could be to transform editing into a string property that corresponds to the id of the comment currently being edited:

        <div>
                <i class="fas fa-pen text-action text-success mr-3" @click="showComment(comment.id)" v-if="user == comment.user_id" v-b-tooltip.hover title="edit"></i>
                <i class="fas fa-times-circle text-danger" v-b-tooltip.hover title="delete" v-if="!editing" v-show="user == comment.user_id"></i>
                <i class="fa fa-times text-action text-danger mr-3" v-if="editing" @click="editing = ''" v-b-tooltip.hover title="cancel editing"></i>
        </div>

        <div v-if="editing == comment.id">
        </div>

   showComment(id) {
       this.editing = id
   },

Answer №2

To improve your editing process, I recommend holding the 'id' of the clicked comment in a variable instead of treating editing as a common factor. You can achieve this by implementing the following code:

 <div v-if="commentId===comment.id">
                <textarea class="form-control" v-model="commentEdited" :id="comment.id" :placeholder="comment.body"></textarea>
                <button class="btn btn-xs btn-success" @click="editComment(comment)">save</button>
            </div>

After storing the selected comment.id in the commentId variable, remember to reset it to an empty value. This approach will enhance your workflow.

This is how I would tackle the situation.

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

Issue with Material UI: Unable to utilize import statement outside of a module due to Select dependency

Hello there! Here is my query: I am currently working on a project using NextJS + React with node. Everything seems to be running smoothly, except for one issue I encounter when reloading a page with a Select component from Material UI. The relevant code ...

Animating progress bars using React Native

I've been working on implementing a progress bar for my react-native project that can be used in multiple instances. Here's the code I currently have: The progress bar tsx: import React, { useEffect } from 'react' import { Animated, St ...

A step-by-step guide to effectively stubbing a dependency within an express middleware using a combination of express-validator, mocha, chai, sinon,

**Edit: Re-created with a simple example that works first: I have an example file and two modules. moduleA has a dependency called moduleB // moduleA.js const ModuleB = require('./moduleB'); function functionA() { return 20 + ModuleB.functio ...

Issues with handler event not firing properly using ASP.net, JavaScript, JQuery, and AJAX, despite successful AJAX implementation

I am currently utilizing a HTTP handler (ASHX) that is being invoked from the UI side through an AJAX function. The objective of this call is as follows: Upon loading the section, the status of the short code on the server will be displayed in the shortco ...

Unleash full rotation capabilities in OrbitControls.js

Currently, I am utilizing OrbitControls.js to rotate the camera around a fixed point. My intention is not to restrict any vertical rotation - my goal is for the camera to smoothly circle the model (orbits around the pivot point). I experimented with remov ...

When the previous textbox is filled, the cursor will automatically move to the button

Utilizing an RFID reader where students tap their ID to display basic info, a hidden button on the form opens a modal with various purposes for selection. The challenge is shifting focus of cursor to the button and automatically clicking it when the last ...

What is causing the error in this particular stream function?

I created a function that logs the provided arguments to the console when piped into it. function logToConsole() { var stream = new Stream.Transform({objectMode: true}), args = [].slice.call(arguments); stream._transform = function (data, ...

Updating an array with complex values in React using the useState hook in

I am working with a long array where I need to update the quantity under the misc array for each person. Each person in the array has a list of miscellaneous items, and each of those items can have their own array with quantities that need to be updated. T ...

"Embedding PHP code within HTML tags, which is then embedded within

Running into an issue within a while loop... echo 'var contentString = '<div id="content" > <div id="bodyContent"> <p>' + $row[name]+ '</p> ...

Execute the code only if the variable is not null

I encountered an issue with my code: setInterval(function() { $.ajax({ url: url, success: function(data, count){ var obj = jQuery.parseJSON(data); var content = obj.results[0].content; }}) }, 2000) The code runs every 2 seconds an ...

Encountering a problem while deploying Vue to GitHub Pages due to issues with vue-router

I encountered some difficulties while deploying a Vue application built with vue-cli v3.0 to GitHub Pages. I utilized subtree to only deploy the dist folder to the gh-pages branch. Initially, the issue was that the assets were not being found, but I resolv ...

Implementing three identical dropdown menus using jQuery and HTML on a single webpage

It seems like I've tangled myself up in a web of confusion. I'm trying to have three identical dropdowns on a single page, each displaying clocks from different cities (so users can view multiple clocks simultaneously). However, whenever I update ...

Using jQuery to loop through a collection

I have a page that displays a list of posts. When a user clicks on the show comments button for a particular post, the comments associated with that post become visible. This functionality is achieved by using this and then searching based on the click loc ...

Vue Resource data loading failed

I've been attempting to create an AJAX request using Vue.js to communicate with a PHP script, however, it doesn't appear to be functioning as expected. Vue: methods: { onSubmit () { if (this.valid) { this.$http.post('http://rem ...

Tips for setting up bidirectional communication with props in a Vue.js component

Within my Vue.js component, I am utilizing the "name" props obtained from the parent component. My goal is to establish a two-way communication between the parent and child components using this props. The parent component code looks like this: <script ...

Creating a feature that uses a button press to initiate an Ajax request based on a specific identifier

I'm looking for the most efficient way to structure a page that involves making Ajax calls. My main issue lies in setting up the event binding for when a user clicks a button. I'm struggling to find a method to pass the ID to the function that t ...

Is there a way to determine the percentage between two specified dates?

If I have a specified start and end date, I am interested in knowing the progress percentage achieved from the start date up to the current date compared to the end date. To put it simply: I would like to determine how far along I am towards the end date i ...

Why does jQuery not work when attempting to access the HTML of paragraphs within the main content using $('#main-content').children('p'

Hello, I'm still getting the hang of jQuery and Stack Overflow. I'm having trouble understanding the differences between DOM elements. My goal is to update the innerHTML of the <p> element, but I'm encountering some unexpected behavior ...

Utilizing JavaScript to handle the value from a selected form

My form is quite simple: <form id="signup"> <div class="form-group"> <input type="text" name="email" placeholder="Email" id="email" required> </div> <div class="form-group"> <input type= ...

Is there a more efficient method for streamlining the Express-Validator middleware in a separate file

In my current project, there is a lot of validation required using Express-Validator. In each file, I find myself repeating the same validation code: //Validation and Sanitizing Rules const validationRules = [ param('tab').isString().isLength({ ...