前言
功能: 实现表格拖拽对数据进行排序.
开发环境:Vue3+ElementUI-Plus+TS+Sortablejs
坑点: 特别需要注意的地方, 代码上备注了…
效果
使用
//安装sortable
npm install sortablejs --save
HTML代码
<template>
<div>
<!-- 此处有坑:row-key="id" row-key必须用,否则排序错乱, 而且要指定用唯一值的字段,别用自定义sort字段.-->
<el-table :data="tableData" row-key="id" class="form_table" style="width: 100%">
<el-table-column label="" width="80">
<el-icon class="move-icon">
<!-- <Switch/> 自定义引用图标 -->
<Switch/>
</el-icon>
</el-table-column>
<el-table-column prop="id" label="ID" width="180"/>
<el-table-column prop="order" label="排序" width="180"/>
<el-table-column prop="name" label="名称"/>
</el-table>
<el-button type="primary" @click="updateSort">更新</el-button>
</div>
</template>
TS代码
<script setup lang="ts">
import Sortable from "sortablejs";
import {nextTick, onMounted, ref} from "vue";
const tableData = ref([
{
id: 1,
order: 1,
name: "胡大1"
},
{
id: 2,
order: 2,
name: "王二2"
},
{
id: 3,
order: 3,
name: "张三3"
},
])
onMounted(() => {
nextTick(() => {
initDropTable()
})
})
const initDropTable = () => {
const sortable1 = Sortable.create(
document.querySelector(".form_table .el-table__body-wrapper tbody") as any,
{
handle: ".move-icon",
onEnd: (event) => {
const {newIndex, oldIndex} = event
//截取被移动的数据
const currRow = tableData.value.splice(oldIndex as any, 1)[0]
//将被移动的数据,插入到移动的位置
tableData.value.splice(newIndex as any, 0, currRow)
//数据处理(复制一份,再对order(自定义排序字段)进行赋值,然后覆盖原数据)
let arr = Array.from(tableData.value);
tableData.value = arr.map((item, index) => {
return {
order: index,
id: item.id,
name: item.name
}
})
},
onStart: (start) => {
// console.log("开始:", start)
}
}
);
}
function updateSort(){
// axios...... tableData已经是最新排序数据了, 根据后端接口处理数据格式后,进行修改即可
}
</script>
CSS代码
<style scoped lang="scss">
.move-icon {
cursor: pointer;
}
</style>