[Vuejs]-Sorting a Vuetify DataTable based on multiple fields

3πŸ‘

It seems that there is no Vuetify 3 equivalent to the custom-sort so far. However, you may use together the sort-by property and update:sortBy event to do what you want.

<template>
  <v-data-table
    v-model:items-per-page="itemsPerPage"
    :headers="headers"
    :items="people"
    :sort-by="sortBy"
    item-value="name"
    @update:sortBy="sortTable"
  ></v-data-table>
</template>

<script>
  export default {
    data() {
      return {
        itemsPerPage: 10,
        headers: [
          { title: 'Name', key: 'name' },
          { title: 'Age', key: 'age' },
        ],
        people: [
          { name: 'Bob', age: 25 },
          { name: 'Ann', age: 25 },
          { name: 'Bob', age: 21 },
          { name: 'Bob', age: 23 },
          { name: 'Ann', age: 31 },
          { name: 'Bob', age: 28 },
          { name: 'Ann', age: 18 },
        ],
        sortBy: [],
      }
    },
    methods: {
      sortTable(evt) {
        // Allows unsorting
        if (!evt.length || evt.length < this.sortBy.length) {
          this.sortBy = []
          return
        }
        const key = evt[0].key
        const order = evt[0].order
        switch (key) {
          case 'name':
            this.sortBy = [
              { key: 'name', order: order },
              { key: 'age', order: 'asc' },
            ]
            break
          case 'age':
            this.sortBy = [{ key: 'age', order: order }] // TODO implement sorting for age column
            break
          default:
            this.sortBy = []
        }
      },
    },
  }
</script>

You can check on the Vuetify playground.

πŸ‘€FloT

0πŸ‘

Based on what you are describing, it sounds like this page might be handy for you, there are both single and multi-sorting props for this element in Vuetify 3.X (it looks like they changed the way they handled it, from "custom-key-sort" to "v-model:sort-by"). Via the docs:

<template>
  <v-data-table
    v-model:sort-by="sortBy"
    :headers="headers"
    :items="desserts"
    class="elevation-1"
  ></v-data-table>
  <v-code class="mt-4">
    <pre>{{ sortBy }}</pre>
  </v-code>
</template>

I may be misunderstanding the question/application, though.

Leave a comment