Tuesday, 6 June 2023

Sorting a Vuetify DataTable based on multiple fields

In Vuetify 2.X it's possible to use the custom-sort prop of VDataTable to implement a sort function that uses multiple fields to sort the rows. Here's an example that sorts a table of people. When the name column is clicked the rows will be sorted by name alphabetically. People with the same name will be sorted in age order

<v-data-table :custom-sort="sortTableRows" :headers="headers" :items="people" />
export default {
  data() {
    const people = [
      {name: 'Bob', age: 25},
      {name: 'Ann', age: 25},
      {name: 'Bob', age: 21}
    ]
    const headers = [
      {text: 'Name', value: 'name'},
      {text: 'Age', value: 'age'}
    ]
    return {headers, people}
  },
  methods: {
    sortTableRows(items, sortBy, sortDesc, locale, customSorters) {
      if (sortBy[0] === 'name') {
        items.sort((row1, row2) => {
          const nameDiff = row1.name.toLowerCase().localeCompare(row2.name.toLowerCase())
          if (nameDiff === 0) {
            return row1.age - row2.age
          }
          return nameDiff
        })
        return items
      } else {
        // TODO implement sorting for age column
      }
    }
  }
}

In Vuetify 3.X the custom-sort prop has been replaced by custom-key-sort. However, this only provides access to the field that is being sorted, so there doesn't seem to be any way to implement the sort function above in Vuetify 3.X. Here's an example of using custom-key-sort to sort the names alphabetically

<v-data-table :custom-key-sort="customSorters" :headers="headers" :items="people" />
methods: {
  customSorters() {
    return {
      name: (name1, name2) => {
        const nameDiff = row1.name.toLowerCase().localeCompare(row2.name.toLowerCase())
        // AFAIK there's no way to access the age field here
        return nameDiff
      },
      age: (age1, age2) => { /* TODO implement sorting for age column */ }
    }
  }
}

Is it possible in Vuetify 3.X to implement a sort function that uses multiple fields to sort a VDataTable's rows?



from Sorting a Vuetify DataTable based on multiple fields

No comments:

Post a Comment