vue.js - 返回并设置反转值
问题描述
我正在为表格进行排序逻辑。
我现在拥有的:
- 可以单击表头对数据进行排序:
<th @click="sort(sortParams.created_at)">Date</th>
排序的方法:
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 }) }
存储所有排序参数的对象:
sortParams: { default: '-created_at', id: 'id', created_at: 'created_at', }
我想要做的:通过axios
.
我的意思是,如果是sortParams.id = 'id'
,它可能会更改为sortParams.id = '-id'
。
我做了一个可以处理这个的方法:
reverseSortParam(param) {
if (param.charAt(0) === '-') {
return param.replace('-', '')
}
return '-' + param
}
我如何reverseSortParam()
在里面使用sort()
?我的意思是,sort()
只接受字符串值,我需要以reverseSortParam()
某种方式传递字符串值的来源。
UPD:一些可能有用的狗屎代码,但在我的项目中没有它的位置:
<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)
})
}
解决方案
我认为你过度设计了这个。您保留了一个潜在的未来排序参数表,但不是当前状态。您还想根据一个值更改此表。最重要的是,您目前只能对单个属性进行排序,但保持(以前的)排序状态,从而为使用它的用户带来有效的随机行为。
考虑更改以下内容:
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
}
}
}
现在,您无需将逻辑分散在各处,只需sort('created_at')
从模板中调用即可。该方法确保我们使用正确的排序参数,getData()
在这种情况下使用这个排序参数
推荐阅读
- c - 如何声明从结构到最终数组的指针
- php - 使用 PHP 在电子邮件中嵌入图像
- node.js - 使用 nodejs 将文件夹内容复制到另一个文件夹
- angular - 为什么在json服务器上调用方法后页面会重新加载
- c# - 如何更改 asp.net 复选框/单选按钮 css 并正确运行 atserver
- java - 如何传递带有黄瓜表达式的字符串?
- c# - 使用 DirectX 和 C# 的 2D 视频游戏。我有哪些选择?
- sql - Hana 正则表达式未按预期工作
- python - 如何在 keras 模型输入中添加“实例键”以在 gcloud ai-platform 中进行批量预测?
- azure-web-app-service - IIS 报告 URI 太长的 500 错误代码