本文共 1567 字,大约阅读时间需要 5 分钟。
通过npm安装Sortable.js:
npm install sortablejs --save
在项目中引入Sortable.js:
import Sortable from 'sortablejs';
在Vue项目中,确保表格结构如下:
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 = 1; const oldItem = tableHeaderList.value[evt.oldIndex - empty]; tableHeaderList.value.splice(evt.oldIndex - empty, 1); tableHeaderList.value.splice(evt.newIndex - empty, 0, oldItem); mykey.value = Math.floor(Math.random() * 1000 + 1); } });}// 行拖拽方法function rowDrop() { 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); } });} row-key:为表格行赋予唯一标识符,避免数据错乱sortable:表头是否支持拖拽排序col类没有冲突的CSSrow-key以避免数据重复{{ row.no }} {{ row.caseNum }}
通过以上步骤,轻松实现Vue项目中的表格拖拽功能。记得在实际使用中根据项目需求进行适当调整,并注意性能优化。
转载地址:http://aojfk.baihongyu.com/