javascriptvue.jssortingvuejs3v-for

Sorting descending after calculating percentage in v-for


In Vue.js for calculating percentage I have the following code:

  <tr>
    <span v-for="(item, index) in data.values" :key="index" >
      {{ item.name }} {{ getPercentage(item.nr) }}
    </span>
  </tr>

And in the percentage method:

methods: {
  getPercentage (number) {
    return number/ this.nrUsers * 100; (ignore the logic)
  }
}

The percentage values are calculated alright but the problem is when displaying them. I would like to have sorted descending and I don't think I can do it from BE because the percentage is calculated here. Any ideas how to do that in Vue.js?


Solution

  • You can create computed property instead of method:

    const app = Vue.createApp({
      data() {
        return {
          items: [{id: 1, nr: 5, name: 'aaa'}, {id: 5, nr: 15, name: 'bbb'}, {id: 2, nr: 7, name: 'ccc'}, {id: 3, nr: 24, name: 'ddd'}, {id: 4, nr: 25, name: 'eee'}],
        };
      },
      computed: {
        sortedItems() {
          return this.items.map(item => {
            let pct = item.nr / 100 * this.items.length;
            return { ...item, pct }
          }).sort((a, b) => b.nr - a.nr)
           
        }
      },
    })
    app.mount('#demo')
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <div id="demo">
      <li v-for="(item, index) in sortedItems" :key="index" >
          {{ item.name }} {{ item.pct }}
        </li>
    </div>