Issue
I'm using vuetify's data tables component to display objects of this schema:
{ date: '2021-12-23T11:12:18.669Z', type: 0, name: 'Meter-234452', temperature: '46', param_value: '23', floor_temp: '23' },
But in my mounted hook I'm overriding the date field to format it as requested by the product owner:
...
moment(date).format('DD.MM.YYYY HH.mm')
I am also grouping the data by the "name" field which works perfectly fine. But sorting the data by date does not work at all, it will only sort it by the day which makes sense.
I tried to specify a custom function in the custom-sort
prop of the component as follows:
customSort (items, sortBy, sortDesc, locale) {
const activeSortColumn = sortBy[0]
const activeSortDesc = sortDesc[0]
items.sort((a, b) => {
if (activeSortColumn === 'date') {
const dateA = moment(a.date, 'DD.MM.YYYY HH.mm').toDate()
const dateB = moment(b.date, 'DD.MM.YYYY HH.mm').toDate()
return activeSortDesc ? dateA - dateB : dateB - dateA
}
return activeSortDesc ? ('' + a[activeSortColumn]).localeCompare(b[activeSortColumn]) : ('' + b[activeSortColumn]).localeCompare(a[activeSortColumn])
})
return items
},
This does work perfectly fine if I don't use grouping, but if I'm grouping and specifying this custom sort function, it'll look like this:
The sorting is still correct, but it also changed the grouping, which kinda makes sense, too. I suppose that it's being sorted and then grouped which causes it to create duplicate groups.
I'm unsure how to solve this, since I'd like to keep the grouping, but also have to provide correct sorting for the date format and all the other columns at once. I noticed that the sortBy parameter will be an array that includes the grouped field aswell if that is being used, so I thought about maybe sorting the data array twice could help?
I appreciate any help!
Solution
I now solved it with a workaround by setting the sort property of the table header to be sorted. It was rather tricky to find this, so in case anyone else runs into this issue, check out the table header example of the v-data-table API.
I used that to specify a separate sort function just for this table header like this:
customSort (a, b) {
return moment(a, this.tableDateFormat).toDate() - moment(b, this.tableDateFormat).toDate()
},
Will work with plain JavaScript dates aswell, but we are using moment for the rest of our project, too.
Answered By - Blade Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.