element-ui中table组件拖拽
HTML结构
<el-table
ref="dragRef"
:data="tableData" // 绑定的数组
v-loading="loading" // 加载动画
width="100%"
:default-sort="{
prop: tableSearchParam.sortField,
order:tableSearchParam.sortType
}" // 默认排列顺序
@sort-change="tableSortChange" // 当表格的排序条件发生变化的时候会触发该事件
:header-cell-style="{textAlign:'center',}" // 标头样式
:cell-style="{textAlign:'center',}" // 表单样式
highlight-current-row // 选中高亮
:row-key="(row) => row.kid" // 行的key值,一定要绑定唯一值
@select-all="selectFreeAll" // 选中全部 这里我是做批量免费,批量删除的,与拖拽无关
@select="selectFree" // 多选,同上
>
<el-table-column type="selection" width="55"></el-table-column> // 复选框
<el-table-column prop="kid" label="ID" width="100"></el-table-column>
<el-table-column prop="sort" label="排序" width="100"></el-table-column>
</el-table>
Vue逻辑
// #1 引入sortable.js,你们也可以npm下载
//<script src="https://www.itxst.com/package/sortable/Sortable.min.js"></script>
// npm install sortablejs --save npm下载
// import Sortable from "sortablejs"; 导入
new Vue({
data() {
tableData:[]
},
methods:{
tableSortChange(column, prop, order) {
if (!column.order) return this.$message({
type: 'warning',
message: '请重试'
}) //偶尔会为null,估计是框架bug
this.tableSearchParam.sortField = column.prop
this.tableSearchParam.sortType = column.order
this.tableUpdateData() // 调用接口更新
},
initSortable() {
let that = this; // 存储Vue实例,后面创建的实例会指向window
// 获取表格row的父节点
const el = this.$refs['dragRef']?.$el.querySelector(
".el-table__body > tbody"
);
// 创建拖拽实例,实例中的this指向window,因此需要借用that
new Sortable(el, {
animation: 150, //动画
disabled: false, // false 启用拖拽
// 开始拖动事件
onStart: () => {
console.log("开始拖动");
},
// 结束拖动事件
onEnd: ({
newIndex,
oldIndex
}) => {
//oldIndex为拖动前索引,newIndex为拖动后索引
// currRow为你删除的那一项,splice返回值是你删除的一个数组
const currRow = that.tableData.splice(oldIndex, 1)[0];
// 拿到你删除的给他放入到你拖动后的位置
this.tableData.splice(newIndex, 0, currRow);
let tableIdList = [] // 将拖拽后的数组id进行重新排序
this.tableData.forEach(item => {
tableIdList.push(item.alivid)
})
// 请求排序接口。这个赋值是,所需参数
this.addItemList = tableIdList
this.sumAddVideo(true, 1)
}
});
},
}
})
以上就是table拖拽的全部逻辑