sortablejs版本 ^1.14.0,框架:vue,UI:element
import Sortable from "sortablejs" // 引入
开始使用:
// 我的接口,请求表格数据 fetchData(){ getUser().then(res => { this.list = res.data.data; this.total = res.data.count; this.$nextTick(() => { // 表格渲染完成,调用拖拽排序方法 this.setSort(); }); }) } setSort() { // 取到表格的表体tbody(这里是elementUI,listData是我el-table的ref) const el = this.$refs.listData.$el.querySelectorAll( '.el-table__body-wrapper > table > tbody' )[0]; this.sortable = Sortable.create(el, { ghostClass: 'sortable-ghost', // Class name for the drop placeholder, setData: function (dataTransfer) { // to avoid Firefox bug // Detail see : https://github.com/RubaXa/Sortable/issues/1012 dataTransfer.setData('Text', ''); }, onEnd: async evt => { const targetRow = this.list.splice(evt.oldIndex, 1)[0]; this.list.splice(evt.newIndex, 0, targetRow); // 如果没有可供用户自定义的排序字段(使用list的index排序),无需进行下面这一步,直接更新list就行 // 我这里用户使用orderNum存贮自己的排序,所以相邻行要进行orderNum交换 if (evt.oldIndex === evt.newIndex) { // 没有交换过,什么也不做 return false; } let start, end; // 从上往下拖拽 if (evt.oldIndex < evt.newIndex) { start = evt.oldIndex; end = evt.newIndex; // 先存最后一个 const endOrderNum = this.list[end].orderNum; for (let i = end; i > start; i--) { const item = this.list[i]; const FItem = this.list[i - 1]; item.orderNum = FItem.orderNum; } // 把最后一个赋值给第一个 this.list[start].orderNum = endOrderNum; // 更新表格,这里暂时没有批量修改接口所以这样写,换成批量修改接口后直接传list全部修改就好 for (let i = end; i >= start; i--) { await updatesysCustomFormDet(this.list[i]); } } else { // 从下往上拖拽 start = evt.newIndex; end = evt.oldIndex; // 先存第一个 const startOrderNum = this.list[start].orderNum; for (let i = start; i < end; i++) { const item = this.list[i]; const LItem = this.list[i + 1]; item.orderNum = LItem.orderNum; } // 把第一个赋值给最后一个 this.list[end].orderNum = startOrderNum; // 更新表格,这里暂时没有批量修改接口所以这样写,换成批量修改接口后直接传list全部修改就好 for (let i = start; i <= end; i++) { await updatesysCustomFormDet(this.list[i]); } } // 更新完成,刷新一下表格 this.fetchData(); }, }); },
更多用法和配置请查阅https://www.npmjs.com/package/sortablejs
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/210266.html原文链接:https://javaforall.net
