Home > Back-end >  How can I sort using v-for in vuejs
How can I sort using v-for in vuejs

Time:09-21

How can I sort using data?

I want to sort in my data using

-start_at -end_at

for example;

data: [
  {
    start_at: '08:00',
    end_at: '09:00',
  },
  {
    start_at: '07:00',
    end_at: '08:00',
  },
  {
    start_at: '06:00',
    end_at: '07:00',
  },
...
],

How can I sort this data from lowest start time (ie 06:00 will be first) to highest?

Thank you guysss !!

CodePudding user response:

use computed property

<template>
  ...
  <div v-for="time in sortedTime">
  </div>
  ...
</template>

<script>
export default {
  data() {
    return {
      time: [],
    }
  },

  computed: {
    sortedTime() {
      return this.time.sort((a,b) => ...)
    }
  }
}
</script>

Docs: https://v2.vuejs.org/v2/guide/computed.html#Basic-Example

CodePudding user response:

EDIT: This will work only if you use vuetify too.

If you are using a v-data-table you should use the custom-sort prop : https://vuetifyjs.com/en/api/v-data-table/#props-custom-sort

Here is an example:

Template:

<v-data-table
    :items="lstActions"
    :headers="headers"
    :search="search"
    :custom-sort="doCustomSort"
>

Script:

public doCustomSort(items: any, index: string[], isDescending: boolean[]) {
    if (index) {
        items.sort((a: any, b: any) => {                
            if (['creationDate', 'modificationdate'].indexOf(index[0]) !== -1) {
                if (isDescending[0]) {
                    return b.informations[index[0]] < a.informations[index[0]] ? -1 : 1;
                }
                return a.informations[index[0]] < b.informations[index[0]] ? -1 : 1;
            }
        });
    }
    return items;
}
  • Related