在 element-ui 官网中,table 组件提供排序功能,但是无法支持多列数据进行排序,那么我们需要如何修改样式呢?
<el-table
:data="tableData"
:header-cell-class-name="handleTheadAddClass"
@sort-change="handleSortChange"
@selection-change="handleSelectionChange"
>
<el-table-column prop="waybillNo" width="140px" label="运单号/合同号" sortable />
<el-table-column prop="vectorQty" width="80px" label="数量" sortable/>
<el-table-column prop="vehicleNo" label="车辆/船名" sortable />
</el-table>
header-cell-class-name:表头单元格的 className 的回调方法,也可以使用字符串为所有表头单元格设置一个固定的 className。
handleTheadAddClass ({ row, column, rowIndex, columnIndex }) {
this.orderArray.forEach(element => {
if (column.property === element.prop) {
column.order = element.order
}
})
},
sort-change:当表格的排序条件发生变化的时候会触发该事件。
handleSortChange ({ column, prop, order }) {
// 取消 order 是 null
if (order) {
let flagIsHave = false
this.orderArray.forEach(element => {
if (element.prop === prop) {
element.order = order
flagIsHave = true
}
})
if (!flagIsHave) {
this.orderArray.push({
prop,
order,
})
}
} else { // order为null时,该字段原本一定在orderArray,去掉即可
let orderIndex = 0
this.orderArray.forEach((element, index) => {
if (element.prop === prop) {
orderIndex = index
}
})
this.orderArray.splice(orderIndex, 1)
}
},
我们可以看到,我们将排序的信息放入到 orderArray 数据中,然后我们根据 orderArray 数据进行处理数据问题。
computed: {
orderBy () {
let result = []
if (this.orderArray.length) {
this.orderArray.forEach(item => {
if (item.prop === 'waybillNo') {
result.push('contractNo')
}
result.push(item.prop)
})
}
return result
},
},