Attach Comments To Specific Post When Click Comments Button Vue Js
I am creating post-comment system where each post will have many comments. I want to fetch the comments of a specific post when click on 'comments' button alike facebook. I am usin
Solution 1:
Since you are initializing comments: [ ]
in the data option it is available to the whole component and you are looping through this comments for every post that is why you get comments displayed for all the posts.
So do it like this
<divclass="post-section"v-for="(post, index) in posts"><post>{{post.body}}</post><button @click="getComments(post, index)"class="btn btn-link">Comments</button><divclass="comment"v-for='comment in post.comments'><p><span> {{comment.comment}}</span></p></div><script>exportdefault {
data() {
return {
posts: [],
}
},
created() {
Post.all(posts =>this.posts = posts)
},
methods: {
getComments(post, index) {
axios.post('getcomments', {id: post.id}).then(response => {
console.log(response.data);
this.$set(this.posts, index, {...post, comments: response.data});
})
}
}
}
What is happening is:
pass the index of the post to the click handler to getComments as 2nd argument.
then use
Vue.$set(your_array, index, newValue)
to update that particular post item by adding extra comments property.es6 spread operator is used to add the extra comments property to the existing post object in the array of posts
if you don't want to use you can use
Object.assign()
like this:this.$set(this.posts, index, Object.assign({}, post, { comments: response.data }));
Here is theexample fiddle
>
Post a Comment for "Attach Comments To Specific Post When Click Comments Button Vue Js"