Home > front end >  How to sort elements in a column in v-data-table
How to sort elements in a column in v-data-table

Time:02-03

I have a v-data-table and the elements in the first columns are some true and false values. By clicking the 'sortable' icon in the header I sort these elements in the column. I want to make that when I open the page, the 'true' values to be sorted first. How can I manage this?

   headers: [
  {
    text: '',
    sortable: true,
    value: 'status',
  }]

Html:

<v-data-table
:pagination.sync="pagination"
:headers="headers"
:items="items"
>
<template>
  <tr>
    <td>
      <v-icon v-if="status">
         {{status}}
      </v-icon>
    </td>
  </tr>
 </template>
 </v-data-table>

Values of status are like: True, False, True, False, False

I want to sort the elements of the column as that: True True False False False

Firstly true values and than false.

CodePudding user response:

You can use external sorting using sortBy and sortDesc:

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: () => ({
    headers: [ { text: '', sortable: true, value: 'status' } ],
    items: [ { status: "True" }, { status: "False" }, { status: "True" } ],
    sortBy: "status",
    sortDesc: true
  })
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">

<v-app id="app">
  <v-data-table 
    :headers="headers" 
    :items="items"
    :sort-by.sync="sortBy"
    :sort-desc.sync="sortDesc"
  >
    <template v-slot:item.status="{ item }">
      <tr>
        <td>
          <v-icon v-if="item.status">{{item.status}}</v-icon>
        </td>
      </tr>
    </template>
  </v-data-table>
</v-app>

CodePudding user response:

You can use sort-by and sort-desc

<v-data-table
  :pagination.sync="pagination"
  :headers="headers"
  :items="items"
  sort-by="status"
  :sort-desc="true"
>
<template>
  <tr>
    <td>
      <v-icon v-if="status">
         {{status}}
      </v-icon>
    </td>
  </tr>
 </template>
 </v-data-table>

You can check more here

  •  Tags:  
  • Related