Skip to content

Instantly share code, notes, and snippets.

@ezequiel9
Created March 25, 2019 04:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezequiel9/43d0cbfcb566a433244093e8f7e1279d to your computer and use it in GitHub Desktop.
Save ezequiel9/43d0cbfcb566a433244093e8f7e1279d to your computer and use it in GitHub Desktop.
Custom Sort Boostrap Table Vue | prop sort-compare
# Your table will have something like this
<b-table show-empty
stacked="sm"
:items="items"
:fields="fields"
:current-page="currentPage"
:per-page="perPage"
:filter="filter"
@filtered="onFiltered"
@row-clicked="editUser"
:sort-compare="customSort" <---- This is the important key
responsive
hover
fixed
>
<template slot="name" slot-scope="row"> <----- Here your complex key that you want to sort for.
<strong>{{row.item.first_name}} {{row.item.last_name}}</strong>
</template>
// another slotss....
.....
</b-table>
// Noy your fields object
data() {
fields: [
{ key: 'id', label: 'ID', sortable: true },
{ key: 'name', label: 'Name', sortable: true}, <----------------- This is how the object look like
{ key: 'contact_number', label: 'Contact Number' },
....
...
{ key: 'active', label: 'Active' }
],
}
// in your data items, will have something like
[
{
id : xx,
first_name : 'asdasd',
last_name : 'asdads',
contact_number : '111111',
active: 1,
.....
},
{
id : yy,
first_name : 'wwwww',
last_name : 'rrrrr',
contact_number : '222222',
active: 1,
.....
}
]
// So your callback for the prop passed into the b-table component will look like this.
methods : {
customSort(a, b, default_key) {
let key;
if(default_key == 'name' ){
key = 'first_name'; <--- see this point. making sure your real key is first_name instead 'name'
}else{
key = default_key;
}
if (typeof a[key] === 'string' && typeof b[key] === 'string') {
// If both compared fields are native numbers
return a[key] < b[key] ? -1 : a[key] > b[key] ? 1 : 0
} else {
// Stringify the field data and use String.localeCompare
return this.toString(a[key]).localeCompare(this.toString(b[key]), undefined, {
numeric: true
})
}
},
toString(value) {
if (!value) {
return ''
} else if (value instanceof Object) {
return keys(value)
.sort()
.map(key => toString(value[key]))
.join(' ')
}
return String(value)
},
}
// noy your table data should work and sort by first name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment