vue.js: reverse the order of v-for loop

寵の児 提交于 2021-02-10 05:28:27

问题


I'm looking for something like the code below to display a list of topics from the array right under the box where user adds them. (newest on top) I know I can unshift instead of pushing to change the order topics are stored in the array but is there a way to keep the original array order and just reverse the displayed topics without triggering the "[Vue warn]: You may have an infinite update loop in a component render function."?

<div class="field add-topic">
    <label for="add-topic">Add a Topic (press Tab):</label>
    <input type="text" name="add-topic" @keydown.tab.prevent="addTopic" v-model="newTopic">
</div>
<div v-for="(tpc, index) in topics.reverse()" :key="index">
    <label for="topic">Topics:</label>
    <input type="text" name="topic" v-model="topics[index]">
</div>

回答1:


the slice method will create a copy of your array. Use it before reverse to only reverse the copy.

topics.slice().reverse();
  <div class="field add-topic">
    <label for="add-topic">Add a Topic (press Tab):</label>
    <input type="text" name="add-topic" @keydown.tab.prevent="addTopic" v-model="newTopic">
  </div>
  <div v-for="(tpc, index) in topics.slice().reverse()" :key="index">
    <label for="topic">Topics:</label>
    <input type="text" name="topic" v-model="topics[index]">
  </div>

More info : https://stackoverflow.com/a/30610528/5671919



来源:https://stackoverflow.com/questions/59828453/vue-js-reverse-the-order-of-v-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!