1、html部分
<el-table
:data="associationList"
style="width: 100%"
@selection-change="temSelectionChange"
v-loading="loading"
row-class-name="drag-row"
@row-contextmenu.prevent
>
<el-table-column type="selection" width="55" />
</el-table>
2、js部分
data() {
return {
associationList: [],
};
},
mounted() {
this.addDragEvents();
},
updated() {
this.$nextTick(() => {
this.addDragEvents();
});
},
methods: {
addDragEvents() {
const rows = document.querySelectorAll('.drag-row');
rows.forEach((row, index) => {
row.draggable = true;
row.ondragstart = (event) => this.handleDragStart(event, index);
row.ondragover = (event) => this.handleDragOver(event);
row.ondrop = (event) => this.handleDrop(event, index);
});
},
handleDragStart(event, index) {
this.draggingIndex = index;
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData('text/plain', index);
},
handleDragOver(event) {
event.preventDefault();
event.dataTransfer.dropEffect = 'move';
},
handleDrop(event, targetIndex) {
const sourceIndex = this.draggingIndex;
if (sourceIndex === targetIndex) return;
const associationList = [...this.associationList];
const [movedItem] = associationList.splice(sourceIndex, 1);
associationList.splice(targetIndex, 0, movedItem);
console.log('拖动前',JSON.stringify(this.associationList),'拖动后',JSON.stringify(associationList));
this.associationList = associationList;
this.draggingIndex = null;
},
}
3、css部分
.drag-row {
cursor: move;
user-select: none;
}
.drag-row:hover {
background-color: #f0f9ff;
}
效果
