vuejs reverse array error infinity loop

Solutions on MaxInterview for vuejs reverse array error infinity loop by the best coders in the world

showing results for - "vuejs reverse array error infinity loop"
Cavan
10 Jan 2017
1<!-- 
2Array.prototype.reverse actually modifies the array it's applied to.
3Vue 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...
4To solve this, use a computed property on a shallow copy of items[] (e.g. using Array destructuring [...this.items] for the reversed list:
5-->
6<template>
7  <div id="app">
8    <ul v-for="item in items">
9      <li>{{ item }}</li>
10    </ul>
11    <hr />
12    <ul v-for="item in itemsReverse">
13      <li>{{ item }}</li>
14    </ul>
15  </div>
16</template>
17
18<script>
19new Vue({
20  el: '#app',
21  data() {
22    return {
23      items: [1, 2, 3, 4]
24    }
25  },
26  computed: {
27    itemsReverse() {
28      return [...this.items].reverse()
29    }
30  }
31})
32</script>