new Vue({
el: '#app',
data: {
sort: {}, // { prop: order, }
tableData: []
},
created() {
this.fetchData()
},
methods: {
handleSortChanged({ column, prop, order }) {
/**
* Here I would like to have null value only in `order`
* to keep a track on my sort object.
* When the header is clicked this method will alternate in
* the folowing values:
*
* Click 1: column: {...}, prop: 'name', order: 'ascending'
* Click 2: column: {...}, prop: 'name', order: 'descending'
* Click 3: column: null, prop: null, order: null
*
* And so it goes....
* For me it makes more sense on click 3 the incoming values:
*
* Click 3: column: {...}, prop: 'name', order: null
*
* Because, with that, I able to know that a sorting column
* has been removed and apply it on may remote request
*/
if (order) {
this.sort[prop] = order
} else {
// This will never work because prop comes null
// and the sort object will always have the last
// sort reference to it
delete this.sort[prop]
}
this.fetchData()
},
async fetchData() {
// sort becomes a string with all fields to be sorted
// separeted by comma, if the order should be
// descending a minus sign is included before the field
// name. ex: prop, -prop2, prop
var sortString = Object.keys(this.sort).reduce((acc, curr) => {
return acc.concat(
`${this.sort[curr] === 'descending' ? '-' : ''}${curr}`
)
}, []).join(',')
console.log('sortString ', sortString)
var { data } = await axios.get(
'https://fakerestapi.azurewebsites.net/api/Authors',
{ params: { sort: sortString } }
)
this.tableData = data
}
}
})
<div id="app">
<el-table :data="tableData" @sort-change="handleSortChanged">
<el-table-column prop="ID" label="ID">
</el-table-column>
<el-table-column sortable="custom" prop="FirstName" label="FirstName">
</el-table-column>
<el-table-column sortable="custom" prop="LastName" label="LastName">
</el-table-column>
</el-table>
</div>