DEV Community

kamasuPaul
kamasuPaul

Posted on

How to add default sort to q-table in quasar framework

Hi, my name is kamasu paul. Today am going to share with you about the default sort of q-table in the quasar framework.

The problem

Of recent, I found out I needed to have the quasar table sorted using a specific column on my table. My goal was to sort the table
and have the most recent items appear on top. Looking at the documentation I couldn't easily figure out how to achieve it.

The Solution.

After several searches, it turns out
The solution is to use the pagination attribute and add it to the table using v-model:pagination="pagination"

<q-table 
row-key="id" 
:rows="transactionsList" 
:columns="columns"
v-model:pagination="pagination"
>
Enter fullscreen mode Exit fullscreen mode

And then in the pagination object, you specify the sortBy attribute

  data() {
    return {
      //... 
      pagination: {
        rowsPerPage: 25,
        sortBy: 'updated_at',
        descending: true,
      }
      //... other properties
    }
  },
Enter fullscreen mode Exit fullscreen mode

For my case, the column is named updated_at and it keeps a javascript date timestamp.
To use a custom sort function add the sort function to the column you want to sort in the columns array, for my case updated_at

const columns = [
  {
    name: "updated_at", label: "Date Updated",
    field: "updated_at", sortable: true,
    sort: (a, b) => a - b
  },
  // ... other columns
];
Enter fullscreen mode Exit fullscreen mode

For my case it's an inline function sort: (a, b) => a - b that compares two timestamps from two rows to sort them.

That's all. Hope it helps

Top comments (1)

Collapse
 
kosis profile image
kosis

Perfect, thanks for the post!