Home  >  Q&A  >  body text

Add count (.length) of each item in options of v-select

I want to add course.length from the api to each item on v-select and display the data to an activity based filter .

For example:

Items in v-select contain options all(count), ## filtered from online.passed #passed(count)notcomplete(count) Filter from online.complete

etc.

vue.js template:

<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>
Response 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
    }
],
P粉197639753P粉197639753186 days ago403

reply all(1)I'll reply

  • P粉787934476

    P粉7879344762024-04-01 10:42:39

    Some observations from the current code you posted:

    • You are checking online.complete === 100 but there is no complete property in the online object. So correct it to completed instead of complete.
    • online.title The closing brace is missing in the expression.

    Now back to the original question:

    Implement counting in the v-select option. You have to convert the items array from an elements array to an objects array.

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

    to

    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)
          }]

    reply
    0
  • Cancelreply