简体   繁体   中英

New Vue components being created at the bottom of the loop

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:

It's working like a charm. 正常工作

When I create a new post在此处输入图像描述

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.

Make sure you use :key together with v-for , preferably binding post's id to it, ie:

<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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM