sortable.js
npm install sortablejs
sortablejs中文网: [http://www.sortablejs.com/options.html]
<template>
<div>
<el-table
:data="tableData"
id="id"
ref="sortableTable"
class="drag-table"
stripe
>
<el-table-column label="姓名" prop="name"></el-table-column>
<el-table-column label="年龄" prop="age"></el-table-column>
<el-table-column label="工龄" prop="workage"></el-table-column>
<el-table-column label="性别" prop="sex"></el-table-column>
</el-table>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import Sortable from 'sortablejs'
const tableData = ref([
{ id: 1, name: '账单', age: '18', workage: '2', sex: '男' },
{ id: 2, name: '账单1', age: '20', workage: '4', sex: '女' },
{ id: 3, name: '中间', age: '18', workage: '2', sex: '男' },
{ id: 4, name: '出发', age: '20', workage: '4', sex: '女' },
{ id: 5, name: '哦哦', age: '18', workage: '2', sex: '男' },
{ id: 6, name: '鱼鱼', age: '20', workage: '4', sex: '女' }
])
const sortableTable = ref(null)
const handleDragEnd = (event) => {
const movedItem = tableData.value.splice(event.oldIndex, 1)[0]
tableData.value.splice(event.newIndex, 0, movedItem)
console.log(tableData.value, 'tableData.value')
}
onMounted(() => {
const tableElement = sortableTable.value.$el.querySelector(
'.el-table__body-wrapper tbody'
)
new Sortable(tableElement, {
animation: 150, // 拖拽时的动画速度,单位为毫秒
handle: '.el-table__row', // 拖拽的手柄元素,这里使用表格的行作为手柄
onEnd: handleDragEnd // 拖拽结束时的回调函数
})
})
</script>
<style lang="less">
.drag-table {
tbody {
td {
&:first-child {
.cell {
padding-left: 0;
display: inline-flex;
align-items: center;
&:before {
content: '';
display: inline-flex;
align-items: center;
background-image: url('./drag.svg') !important;
background-position: 0 center !important;
background-repeat: no-repeat !important;
cursor: grab;
width: 15px;
height: 15px;
margin-right: 5px;
}
}
}
}
}
.blue-background-class {
td {
background: #5a8cf0 !important;
border-top: 1px solid #dcebff;
border-bottom: 1px solid #dcebff;
color: #fff;
}
}
.dragHandle {
cursor: grab !important;
}
.grabbing,
.isSelected,
.isSelected > .dragHandle {
cursor: grabbing !important;
}
}
</style>