[Vuejs]-Run loop backward in template in vuejs

2👍

Solution 1: Reverse array directly in template

You can actually reverse the array directly in your template before iterating through it, using recent.slice().reverse(). Using .slice() is necessary because this.recent is actually not an array per se. However, I do not prefer this method because it means placing logic in your template.

<template>
 <li v-for="r in recent.slice().reverse()">
  {{r}}
 </li>
</template>
new Vue({
  el: '#list',
  data: {
    recent: [
      'Lorem',
      'ipsum',
      'dolor',
      'sit',
      'amet'
    ]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<ul id="list">
  <li v-for="r in recent.slice().reverse()">
    {{ r }}
  </li>
</ul>

Solution 2: Use a computed property

As what @vbranden has said, you can simply reverse an array in a method and use it in v-for. This is my preferred method.

new Vue({
  el: '#list',
  data: {
    recent: [
      'Lorem',
      'ipsum',
      'dolor',
      'sit',
      'amet'
    ]
  },
  computed: {
    recentReversed: function() {
      return this.recent.reverse();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<ul id="list">
  <li v-for="r in recentReversed">
    {{ r }}
  </li>
</ul>
👤Terry

2👍

You should use Array.prototype.reverse()

Source : link

In your computed

export default Vue.extend({
        name: 'mainActivity',
        data (){
            return{
                stuff: ['a', 'b', 'c', 'd']
            }
        },
      computed:{
              reverseArray(){return this.stuff.reverse()}
       },
        created(){}
    })

HTML

<template>
 <li v-for="r in reverseArray">
  {{r}}
 </li>
</template>

0👍

There is no for-loop form of v-for. There is a range form, which you can use to get the effect you want (with a little simple math).

You could do the same thing with a computed, as vbranden noted in his comment.

new Vue({
  el: '#app',
  data: {
    stuff: ['a', 'b', 'c', 'd']
  },
  computed: {
    stuffIndexCountdown() {
      return this.stuff.map((_, i) => i).reverse();
    }
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
  <div v-for="i in stuff.length">
    {{stuff.length - i}}
  </div>
  <hr>
  <div v-for="i in stuffIndexCountdown">
    {{i}}
  </div>
</div>
👤Roy J

Leave a comment