Reputation: 59
I'm fetching comments from api. and I'm trying to edit a comment from the list.
When i click edit i show a text area inside the comment box and a button to save the comment . which is working nicely.
The problem is when i click edit the edit textarea gets applied to all comment boxes :|
<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 show comment 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
is a boolen.
when i click edit it should only open the textarea for the current comment only . not all the comments :\
I really cant figure this out .Any help is appreciated .
Upvotes: 0
Views: 903
Reputation: 823
the reason is you are having editing as a common variable, i suggest you instead to carry a variable that holds the 'id'of your clicked comment, so if you have something like
<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>
where commentId is the variable into which you store the selected comment.id after that make it '' empty...
this would be my approach
Upvotes: 1
Reputation: 893
Its because editing
boolean is used by all of the components so when setting it to true, all comments show. You could change editing to a string property that is equal to the id of the comment 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
},
Upvotes: 2