Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort date columns in bootstrap-vue if using formatter for displaying?

I have a table with date objects, which I transform for display like this:

{
   key: "date",
   formatter: (value, key, item) => {
     return moment(value).format("L");
   },
   sortable: true
}

This breaks the sorting function because is a localized string. I'd like to do something like

 sortingKey: value=>value

To override the string sorting of the rendered date and go back to sorting by dates, but I can't find anything like that.

Update: This is already sorted out, but to me the solution is not pretty. A prettier solution would have been:

field: {
  key: 'date',
  sorter: (value, item, fieldMeta) => {
    // returns something that reacts to <
    // key == fieldMeta.key
    // default (current) implementation
    return fieldMeta.formatter ? fieldMeta.formatter(value, fieldMeta.key, item) : value;
  }
like image 271
estani Avatar asked Jul 16 '19 19:07

estani


1 Answers

The sort-compare function will be your fiend. the basic sort compare method compares two values, and requires a minimum of three arguments: item a, item b, and the field key being sorted on. Note a and b are the entire row data objects being compared.

For your above example, do the following:

export default {
  // ...
  methods: {
    mySortCompare(a, b, key) {
      if (key === 'date') {
        // Assuming the date field is a `Date` object, subtraction
        // works on the date serial number (epoch value)
        return a[key] - b[key]
      } else {
        // Let b-table handle sorting other fields (other than `date` field)
        return false
      }
    }
  }
  // ...
}
<b-table :items="items" :fields="fields" :sort-compare="mySortCompare">
  <!-- ... -->
</b-table>
like image 72
Troy Morehouse Avatar answered Oct 09 '22 08:10

Troy Morehouse