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;
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With