iView本身的Table在不分页数据量稍微大一点的时候,会使整个页面操作起来特别卡顿,其实element也有这个问题。
故采用vxe-table
1. 环境
- vue 2.6.12
- vxe-table 3.3.8
2. 自定义列排序
列排序的时候,降序的时候null值排在最前面,升序null值排在最后面。这是不符合常理的。所以使用自定义列排序方法。
即sort-config中的sortMethod。
用的方法比较原始,先把null值的行过滤出来,然后根据根据升序降序添加到结果数组数组中。
需要注意的是,数字和字符串应该分别排序。
<vxe-table
:sort-config="{
trigger: 'cell',
orders: ['desc', 'asc', null],
sortMethod: customSortMethod
}"
>
<vxe-table-column
sortable
>
</vxe-table-column>
</vxe-table>
customSortMethod({ data, column, property, order }) {
let data1 = data.filter((item)=>{return item[column.property] === undefined})
let data2 = data.filter((item)=>{return item[column.property] !== undefined})
let tmpData = []
if(order === 'desc') {
tmpData = data2.sort((a,b)=>{
if(util.typeOf(a[column.property]) === 'number'){
return b[column.property] - a[column.property]
}else{
return b[column.property].localeCompare(a[column.property]);
}
}).concat(data1)
}
if(order === 'asc'){
tmpData = data1.concat(data2.sort((a,b)=>{
if(util.typeOf(a[column.property]) === 'number'){
return a[column.property] - b[column.property]
}else{
return a[column.property].localeCompare(b[column.property]);
}
}))
}
return tmpData;
}
3. 使用vxe-toolbar自定义导出按钮
<vxe-toolbar ref="xToolbar1">
<template #tools>
<Button shape="circle" icon="md-download" @click="excelExport">导出</Button>
</template>
</vxe-toolbar>
<vxe-table>
</vxe-table>
excelExport() {
// 前端导出方法
}
需要注意的是,使用自定义导出的时候,前端页面是排序的,但是导出的文件还是原顺序。
为了解决这个问题,另外定义一个数组用来保存排序后的数据。伪代码如下:
data(){
return{
tableData:[],
excelData:[]
}
},
mounted:{
this.initData()
},
methods:{
initData(){
// axios 获取数据
this.tableData = resultArray
this.excelData = resultArray
},
// 上文中提到的自定义排序方法
customSortMethod({ data, column, property, order }) {
// ..... 自定义排序方法
this.excelData = tmpData
return tmpData;
}
}
4. 使用div/span循环产生列时,列顺序异常
异常的表现有两个:
- 表中既有循环产生的列,又有非循环产生的列(序号列),序号列顺序异常,命名定义的时候在前面,展示在后面。
- 嵌套列vxe-table-colgroup 中的child列顺序异常
大概如下图:
错误代码:
<span v-for="(item,index) in frontColumn"
:key="item.key">
<vxe-table-column
:field="item.key"
:title="item.title"
>
</vxe-table-column>
</span>
正确代码:应该直接在column上循环
<vxe-table-column
v-for="(item,index) in frontColumn"
:key="item.key"
:field="item.key"
:title="item.title"
>
</vxe-table-column>
这是个低级错误,事后反思了很久。读api文档要心细些。
君子慎独,不欺暗室。