1👍
✅
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>
0👍
You can’t sort the items at the time of rendering. You first need to sort your data in descending order and then you can render.
According to your comment, you can surely sort the items first.
- Fetch the data from API.
- Loop over data items and calculate their percentage.
- Sort the data in descending order according to the percentage value.
- And last, render this sorted data in the template.
Hope this gives some direction.
Source:stackexchange.com