3

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 Answer 1

10

the method toReversed method will create a reversed copy of your array.

topics.toReversed();
  <div v-for="(tpc, index) in topics.toReversed()" :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://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toReversed

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Pierre , your code didn't actually do it for me but using slice().reverse() to create a new array and iteraring on this one instead works perfectly.
I would prefer a computed property in this case to do the reversal and copying logic, then you can just use v-for on the computed prop name. You can also use the spread operator to create a copy: [...topics].reverse().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.