我这里使用的是 sortablejs 插件;
安装命令: npm install sortablejs --save
注意点:
你的表格数据中要有id作为key去使用;
<div class="draggable">
<el-table row-key="id" :data="form.tableData" style="width: 100%" max-height="250">
<el-table-column type="index" width="80" label="数源顺序" />
<el-table-column
v-for="(column, index) in oldList"
:key="index"
:prop="column.prop"
:label="column.label"
:width="column.width"
show-overflow-tooltip
/>
<el-table-column fixed="right" label="操作" min-width="260">
<template #default="scope">
<el-button
type="primary"
@click="handleEdit(scope.row)"
link>
编辑
</el-button>
<el-button
link
type="danger"
@click.prevent="deleteRow(scope.$index)"
>
删除
</el-button>
<el-button
v-if="scope.$index !== 0"
type="primary"
@click.prevent="moveUp(scope.row, scope.$index)"
link>
上移
</el-button>
<el-button
v-if="scope.$index !== form.tableData.length - 1"
type="primary"
@click.prevent="shiftDown(scope.row, scope.$index)"
link>
下移
</el-button>
<el-button
v-if="title === '数源配置' && scope.row.status === '0'"
type="primary"
@click.prevent="enable(scope.row)"
link>
启用
</el-button>
<el-button
v-if="title === '数源配置' && scope.row.status === '1'"
type="primary"
@click.prevent="forbidden(scope.row)"
link>
禁用
</el-button>
</template>
</el-table-column>
</el-table>
</div>
<script setup>
import Sortable from 'sortablejs';
const form = ref({
tableData: [
{ id: 1, status: '0', name: '哈哈哈111' },
{ id: 2, status: '1', name: '哈哈哈222' },
{ id: 3, status: '0', name: '哈哈哈333' },
{ id: 4, status: '0', name: '哈哈哈444' }],
});
const oldList = ref([]);
const columns = ref([
{ prop: 'state', label: '数源英文名称', width: '200' },
{ prop: 'name', label: '数源中文名称', width: '200' },
{ prop: 'name', label: '字段名称', width: '200' },
{ prop: 'name', label: '所属部门', width: '200' },
{ prop: 'state', label: '业务系统名称', width: '200' },
{ prop: 'state', label: '数源说明', width: '200' }
]);
// 行拖拽
const rowDrop = () => {
// 要拖拽元素的父容器 tbody
const tbody = document.querySelector('.draggable .el-table__body-wrapper tbody')
Sortable.create(tbody, {
// 可被拖拽的子元素
draggable: ".draggable .el-table__row",
onEnd({ newIndex, oldIndex }) {
// newIndex 拖动到的新的索引
// oldIndex 没拖动前的索引
const currRow = form.value.tableData.splice(oldIndex, 1)[0]
form.value.tableData.splice(newIndex, 0, currRow)
}
});
};
onMounted(() => {
oldList.value = JSON.parse(JSON.stringify(columns.value))
rowDrop()
})
</script>