WillMac997
WillMac997

Reputation: 143

Looping a number range in reverse using v-for?

I've got a simple v-for loop that loops 5 times from 1 to 5, however I want to loop in reverse from 5 to 1? Is this possible? I'm adding a class to a list item and I want to fill the list items from most full to least full from the top

Adding | reverse doesn't work

<div v-for="n in 5 | reverse" :key="n.index">
    <div class="container">
        <ul class="rating">
            <li :class="[ (n <= 5) ? 'fill' :'' ]"></li>
            <li :class="[ (n <= 4) ? 'fill' :'' ]"></li>
            <li :class="[ (n <= 3) ? 'fill' :'' ]"></li>
            <li :class="[ (n <= 2) ? 'fill' :'' ]"></li>
            <li :class="[ (n <= 1) ? 'fill' :'' ]"></li>
        </ul>
        <span>{{ n }}</span>
    </div>
</div>

Upvotes: 2

Views: 4526

Answers (2)

Mohamed Adel
Mohamed Adel

Reputation: 221

simply

 <div v-for="i in 5" :key="i" class="my-1 pointer d-flex justify-content-between">
   <div>{{6-i}}</div>
 </div>

Upvotes: 5

tao
tao

Reputation: 90188

Array filters no longer work in v2. But you can make your own reversed method.

"n in [...Array(5).keys()].slice().reverse()" works, so:

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: '#app',
  methods: {
    reverseKeys(n) {
      return [...Array(n).keys()].slice().reverse()
    }
  }
})
.rating, .container {
  display: flex;
  list-style-type: none;
  margin: 0;
}
.rating li {
  width: 1rem;
  height: 1rem;
  border: 1px solid #ddd;
  border-radius: .5rem;
  margin: .1rem;
}
.fill {
  background-color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="n in reverseKeys(5)" :key="n">
      <div class="container">
          <span>{{ n + 1 }}</span>
          <ul class="rating">
              <li v-for="key in 5" :class="{ fill: key <= n + 1 }" :key="key" />
          </ul>
      </div>
  </div>
</div>

Upvotes: 8

Related Questions