1、安装
npm install sortablejs --save
2、引入
import Sortable from 'sortablejs';
3、使用
- 表格表头必须加
row-key
,否则会出现排序错乱 - 完整代码
table.vue
<el-table v-loading="loading"row-key="id":height="tableHeight"ref="tableRef"borderstripesize="small":data="receiptDataList":row-class-name="setRowColor"show-summary:summary-method="getSummaries"@selection-change="handleSelectionChange"><el-table-column type="selection" width="45" align="center"/><el-table-columnv-for="(item, index) in tableHeaderList":key="`col_${index}_${mykey}`":prop="item.prop":label="item.label":width="item.width":sortable="item.sortable":show-overflow-tooltip="item.overflow"align="center"><template #default="{row}" v-if="item.label === '收款编码'"><span>{{ row.no }}</span></template><template #default="{row}" v-if="item.label === '箱号'"><span>{{ row.caseNum }}</span></template>.......</el-table-column>
</el-table>
onMounted(() => {columnDrop()rowDrop()
})
//列拖拽:列拖拽方法实际上就是修改表头数据的值
const mykey = ref(0)
function columnDrop() {const wrapperTr = document.querySelector('.el-table__header-wrapper tr');Sortable.create(wrapperTr , {animation: 180,delay: 0,onEnd: evt => {// 跳过显示的列数量,如开头我们用了一个多选框const empty = 1const oldItem = tableHeaderList.value[evt.oldIndex- empty];tableHeaderList.value.splice(evt.oldIndex- empty, 1);tableHeaderList.value.splice(evt.newIndex- empty, 0, oldItem);//防止表头数据改变,但表头未重新渲染//在自定义表头的时候,由于是用的v-for循环生成的,因此会给每个循环体一个固定的key,导致数据频繁异步更新时,因为这个key没有变,所以el-table觉得表头数据是没有变化的,因此就只更新了整体表格数据、key值有变化的列的表头。mykey.value = Math.floor(Math.random()*1000+1) }});
}//行拖拽:行拖拽方法实际上就是修改this.tableData的值
function rowDrop() {// 要侦听拖拽响应的DOM对象const tbody = document.querySelector('.el-table__body-wrapper tbody');Sortable.create(tbody, {// 结束拖拽后的回调函数onEnd({newIndex, oldIndex}) {console.log('拖动了行,当前序号:' + newIndex);const currentRow = receiptDataList.value.splice(oldIndex, 1)[0];receiptDataList.value.splice(newIndex, 0, currentRow);}})
}