感觉行拖拽还是听常用的一个功能,但是好像没有看到相关的分享,就尝试研究了下
我这里是使用sortablejs结合自定义列来实现
1. 自定义列:
// curd.js
export const crudOptions = vm => {
return{
...
columns: [
...
{
title: '拖动',
key: 'handleMove',
align: 'center',
show: false,
width: 50,
form: {
disabled: true
},
component: {
render: (h, scope) => {
return (<i class="el-icon-s-grid row-drag-handle" style="font-size: 24px;"></i>)
}
}
},
]
}
}
2. 结合 sortablejs 实现拖拽
<!-- index.vue -->
...
<script>
import Sortable from 'sortablejs'
export default {
...
mounted () {
this.initSortable()
},
methods: {
initSortable () {
const tbody = this.$refs.d2Crud.$el.querySelector('.vxe-table--body-wrapper tbody')
if (tbody) {
Sortable.create(tbody, {
handle: '.row-drag-handle', // handle控制拖拽的手柄
onEnd: this.handleRowDragEnd // 处理提交数据
})
}
},
handleRowDragEnd (evt) {
const { oldIndex, newIndex } = evt
if (oldIndex !== newIndex) {
const form = this.getSearch().getForm()
const params = { ...form }
const { current: page, size: limit } = this.crud.page
const query = { oldIndex, newIndex, page, limit }
api.Reorder(query, params)
.then((ret) => {
this.$message.success(ret.msg)
// 调整列表数据(这里不调换的话,编辑会发现这一行还是老数据)
const rowData = this.crud.list.splice(oldIndex, 1)[0]
this.crud.list.splice(newIndex, 0, rowData)
this.$forceUpdate()
})
}
},
}
}
</script>
3. 换序接口Reorder的实现
关于这一部分,我没想到什么更好的办法,只能通过批量修改sort去实现,各位大佬有什么更好地方式还请多多指点
@swagger_auto_schema(request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
required=['old_index', 'new_index']
), operation_summary='调整排序')
@action(methods=['put'], detail=False)
def reorder(self, request, *args, **kwargs):
request_data = request.data
old_index = request_data.get('oldIndex', None)
new_index = request_data.get('newIndex', None)
page = request_data.get('page', None)
size = request_data.get('limit', None)
if not (isinstance(old_index, int) and isinstance(new_index, int) and isinstance(page, int) and isinstance(size,
int)):
return ValueError("请求参数异常")
queryset = self.filter_queryset(self.get_queryset())
offset = (page - 1) * size
item = queryset[offset + old_index]
item.sort = queryset[offset + new_index].sort + 1
item.save()
ids_to_update = [obj.id for obj in queryset[offset + new_index:] if obj.id != item.id]
queryset.filter(id__in=ids_to_update).update(sort=F("sort") + 2)
return SuccessResponse(data=[], msg="排序成功")
第一次写分享,有什么不到之处,还请多多指正