引入第三方插件layui-soul-table
layui.config({
base: 'static/modules/', // 第三方模块所在目录
version: 'v1.6.4' // 插件版本号
}).extend({
soulTable: 'soulTable/soulTable',
tableChild: 'soulTable/tableChild',
tableMerge: 'soulTable/tableMerge',
tableFilter: 'soulTable/tableFilter',
excel: 'soulTable/excel',
})
开启表格行拖动
layui.use(['form', 'table','soulTable'], function () {
var table = layui.table,
form = layui.form,
soulTable = layui.soulTable
soulTable.config({
rowDrag: true
})
...
})
前端实现
-
表格加载
table.render({ ... , initSort: { field: 'numbers', type: 'asc', } , rowDrag: { before: function (obj) { var oldIndex = obj.oldIndex var newIndex = obj.newIndex var currentRecord = obj.cache if (obj.oldIndex == obj.newIndex) { return false } updateLayerRelationNumbers(oldIndex, newIndex, currentRecord) } } , parseData: function (res) { return { "code": 0, "count": res.data.total, "data": res.data.records, "size": res.data.size, } } ... done: function(res, curr, count) { soulTable.render(this) // 在done中开启 currentPage = curr; // 当前页码值(全局变量) currentSize = res.size; // 分页数目(全局变量) ... } })
-
numbers字段批量更新函数
/** * 拖拽图层关系表行数据时,更新numbers字段 * 向上拖动,oldIndex更新为newIndex,[newIndex到oldIndex)在原来基础上 + 1 * 向下拖动, oldIndex更新为newIndex,(oldIndex到newIndex]在原来基础上 - 1 * * @param oldIndex 拖拽前的行索引 * @param newIndex 拖拽后的行索引 * @param currentRecord 当前页数据 */ function updateLayerRelationNumbers(oldIndex, newIndex, currentRecord) { var configLayerRelationlist = [] var targetRecord, changeRecord targetRecord = currentRecord.filter((row, index) => { return index == oldIndex }) var configLayerRelation = { "id": targetRecord[0].id, "numbers": newIndex + currentSize * (currentPage - 1) + 1 // 下标从1开始 } configLayerRelationlist.push(configLayerRelation) changeRecord = currentRecord.filter((row, index) => { if (newIndex < oldIndex) { // 向上方拖动 return index >= newIndex && index < oldIndex } else { // 向下方拖动 return index > oldIndex && index <= newIndex } }) changeRecord.forEach(function (row) { var configLayerRelation = { "id": row.id, "numbers": newIndex < oldIndex ? row.numbers + 1 : row.numbers - 1 } configLayerRelationlist.push(configLayerRelation) }) postDataToServer('/layerGroup/updateLayerRelationNumbers', JSON.stringify(configLayerRelationlist), function (res) { if (res.success == true) { ... } else { ... } }) }
后端实现
-
controller
/** * 根据id列表批量更新序号 * * @param configLayerRelationList * @return */ @RequestMapping("/updateLayerRelationNumbers") public ResponseData updateLayerRelationNumbers(@RequestBody List<ConfigLayerRelation> configLayerRelationList) { boolean flag = configLayerRelationService.updateBatchById(configLayerRelationList); if (flag) { return successWithData(true); } else { return fail("更新失败!"); } }
注意:Mybatis-Plus会自动忽略实体中为null的属性,不会去更新他们