在v-select的选项中添加count(.length)每个项目



我想将计数course.length从api添加到v-select上的每个项option,并将数据显示到基于活动的过滤器。

例如:v-select中的项目包含选项all(count)、从online.passed过滤的passed(count)、从online.complete过滤的not complete(count)等。

vue.js模板:

<template>
<v-select
v-model="filter"
:items="items"
></v-select>
<v-card v-for="online in onlineCourse" :key="online.id">
<v-card-title>{{online.title}</v-card-title>
<p v-if="online.complete === 100">{{online.complete}}%</p>
<p v-else-if="online.complete < 100 && online.complete > 0">{{online.complete}}%</p>
<p v-else>{{online.complete}}%</p>
</v-card>
</template>
<script>
data () {
return {
onlineCourse: [],
filter: 'All',
items: [
'All',
'passed',
'not complete',
],
}
}
method: {
async getDataOnline () {
try {
const request = await Axios.get('v1/courses')
this.onlineCourse = request.courses
} catch (error) {
console.log(error.message);
}
}
}
</script>

响应JSON:

"courses": [
{
"id": 1,
"title": "title1",
"passed": false,
"completed": 0
},
{
"id": 2,
"title": "title2",
"passed": true,
"completed": 100
},
{
"id": 3,
"title": "title3",
"passed": false,
"completed": 50
}
],

您发布的当前代码中的少数观察结果:

  • 您正在检查online.complete === 100,但在线对象中没有complete属性。因此,将其更正为completed而不是complete
  • online.title表达式中缺少大括号

现在来谈谈最初的问题:

实现v-select选项中的计数。您必须将项目数组从array of elements转换为array of objects

items: ['All', 'passed', 'not complete']

items: [{
name: 'All',
count: this.onlineCourse.length
}, {
name: 'passed',
count: this.onlineCourse.filter((course) => course.passed)
}, {
name: 'not complete',
count: this.onlineCourse.filter((course) => course.completed === 0)
}]

最新更新