Reputation: 2398
I'm making sorting logic fo a table.
What I have now:
<th @click="sort(sortParams.created_at)">Date</th>
method which does sort:
sort(param) {
let that = this
axios.get(process.env.API_BASE_URL + process.env.API_BASE_VERSION + 'data?sort=' + param + '&page=' + that.tableData.current_page)
.then(function (response) {
that.tableData = response.data
})
}
an object where all sort params are stored:
sortParams: {
default: '-created_at',
id: 'id',
created_at: 'created_at',
}
What I want to do: reverse sort param after successful data fetch via axios
.
I mean if it was sortParams.id = 'id'
, it might be changed to sortParams.id = '-id'
.
I made a method which can handle this:
reverseSortParam(param) {
if (param.charAt(0) === '-') {
return param.replace('-', '')
}
return '-' + param
}
How can I use reverseSortParam()
inside sort()
? I mean, sort()
accepts only string value, and I need to pass the source of the string value to reverseSortParam()
somehow.
UPD: Some shitcode which might work, but there is no place for it in my project:
<th @click="sort(sortParams.created_at, 'created_at')">Date</th>`
sort(param, paramName) {
let that = this
axios.get(process.env.API_BASE_URL + process.env.API_BASE_VERSION + 'data?sort=' + param + '&page=' + that.tableData.current_page)
.then(function (response) {
that.tableData = response.data
that.sortParams[paramName] = that.reverseSortParam(param)
})
}
Upvotes: 1
Views: 301
Reputation: 20737
I think you are over-engineering this. You are keeping a table of potential future sort parameters, but not the current state. You also want to change this table based on a value. On top of that you can currently only sort on a single attribute, but keep the (previous) state of sorting, causing effectively random behaviour for the user that is using it.
Consider changing the following:
data () {
return {
// Maps local names to api names
sortMap: {
created_at: 'created_at',
time: 'datetime',
id: 'id'
},
// The default sort
sortParam: 'created_at'
},
methods: {
async sort (localName) {
// Figure out if we need to inverse the current sort
const currentSort = this.sortParam.replace('-', '');
// Set the current sort
if (currentSort === this.sortMap[localName]) {
this.sortParam = `-${this.sortParam}`.replace('--', '');
} else {
this.sortParam = this.sortMap[localName];
}
this.getData()
},
async getData () {
// You probably want to factor out the api calls to their own file anyway
this.tableData = await axios.get(..).data
}
}
}
Now instead of having your logic scattered around the place, you simply call sort('created_at')
from your template. The method makes sure we use the correct sorting parameter and getData()
in this case uses this sorting parameter
Upvotes: 1