Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs v-for infinite update loop using Array.prototype.reverse()

Tags:

loops

vuejs2

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: []
            }
       }
 }

....

like image 450
Di Mi Avatar asked Mar 24 '18 16:03

Di Mi


1 Answers

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>
like image 76
connexo Avatar answered Sep 24 '22 03:09

connexo