Reputation: 2580
I have a component called post-index
which shows all the posts. Within it, I have another component which handles individual post, namely, post-view
. Inside it, I have another component which handles likes and dislikes. It is called post-like
.
Everything works fine as expected but if I add a new post to the existing array (using .unshift()
) everything misbehaves.
For eg:
See? It's highlighting the like button even though it is not been liked by the user. After many trials I have found that it is duplicating the like value (true or false) from the below post. Which means the component is not being created for the new post, instead at the bottom. Is there any solution for this problem?
All I have inside the post-like
component is a data property called like
. Which handles the like and dislike actions.
If I am not wrong, Vue is re-rendering from the top and adding new components to the bottom. How can I solve this issue?
Please ask if you want any other information about this issue.
Upvotes: 2
Views: 141
Reputation: 3653
Make sure you use :key
together with v-for
, preferably binding post's id to it, i.e:
<ul>
<li v-for="(post, index) in posts" :key="post.id">
<!-- post stuff here -->
</li>
</ul>
See this for reference: https://v2.vuejs.org/v2/guide/list.html#key
Upvotes: 2