英文:
Sorting descending after calculating percentage in v-for
问题
在Vue.js中,用于计算百分比的代码如下:
<tr>
<span v-for="(item, index) in data.values" :key="index">
{{ item.name }} {{ getPercentage(item.nr) }}
</span>
</tr>
百分比计算方法如下:
methods: {
getPercentage(number) {
return number / this.nrUsers * 100; //(忽略逻辑)
}
}
百分比值已经正确计算,但问题出现在显示时。我希望按降序排序它们,但我不认为可以从后端实现排序,因为百分比是在这里计算的。有没有在Vue.js中实现这个的想法?
英文:
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?
答案1
得分: 1
你可以创建计算属性而不是方法:
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>
英文:
You can create computed property instead of method:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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')
<!-- language: lang-html -->
<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>
<!-- end snippet -->
答案2
得分: 0
无法在渲染时对项目进行排序。您首先需要按降序对数据进行排序,然后才能进行渲染。
根据您的评论,您肯定可以首先对项目进行排序。
- 从API获取数据。
- 循环遍历数据项目并计算它们的百分比。
- 根据百分比值将数据降序排序。
- 最后,在模板中呈现这些排序后的数据。
希望这提供了一些指导。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论