6

I have such an error I can not solve in any way

[Vue warn]: You may have an infinite update loop in a component render function. found in

in component use

    <div  v-for="item in items">
         {{item.title}}
    <div>
.................
    <div  v-for="item in items.reverse()">
         {{item.title}}
    <div>

export default {
   name: "component-name"
   data(){
        return { 
            items: []
            }
       }
 }

....

1 Answer 1

12

Array.prototype.reverse actually modifies the array it's applied to.

Vue picks up this change and triggers both v-for to re-evaluate, triggering another .reverse(). That triggers Vue to re-render, causing it to .reverse() etc etc etc etc etc etc etc etc etc etc...

To solve this, use a computed property on a shallow copy of items[] (e.g. using Array destructuring [...this.items] for the reversed list:

new Vue({
  el: '#app',
  data() {
    return {
      items: [1, 2, 3, 4]
    }
  },
  computed: {
    itemsReverse() {
      return [...this.items].reverse()
    }
  }
})
<script src="https://unpkg.com/vue"></script>
<div id="app">
  <ul v-for="item in items">
    <li>{{item}}</li>
  </ul>
  <hr />
  <ul v-for="item in itemsReverse">
    <li>{{item}}</li>
  </ul>
</div>

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

Comments

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.