1.简介:
Sortable.js是一款优秀的js拖拽库,支持ie9及以上版本ie浏览器和现代浏览器,也可以运行在移动触摸设备中。不依赖jQuery。支持 Meteor、AngularJS、React、Vue、Knockout框架和任何CSS库,如Bootstrap、Element UI。你可以用来拖拽div、table等元素。
2.官网:
(1)中文文档教程:sortable.js中文文档 - itxst.comhttps://www.itxst.com/sortablejs/neuinffi.html
(2)直观了解及效果使用:Sortable.js中文网http://www.sortablejs.com/
(3)详细文档教程:sortablejs - npmhttps://www.npmjs.com/package/sortablejs
3.使用:
(注:row-key==>值数据中id,id:标记表格行)
<template>
<div class="main-content">
<el-table
ref="multipleTable"
:data="tables"
border
fit
highlight-current-row
row-key="id"
id="tableRowDrop"
>
<el-table-column>11</el-table-column>
<el-table-column>22</el-table-column>
<el-table-column>33</el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs' //下载插件命令:npm install sortablejs --save
export default {
data(){
return{
tables:[], //保存表格显示数据
rowSortOld:[], //保存表格行拖动前:id顺序数组(旧)
rowSortNew:[] //保存表格行拖动后:id顺序数组(新)
}
},
mounted() {
//阻止默认行为
document.body.ondrop = function (event) {
event.preventDefault();
event.stopPropagation();
};
//列表行拖拽后顺序数组
this.rowDrop();
},
methods: {
//表格行拖拽
rowDrop() {
//获取表格对象
const tbody = document.querySelector('#tableRowDrop tbody');
const _this = this; //(注意此处引用)
Sortable.create(tbody, {
onEnd({ newIndex, oldIndex }) {
const currRow = _this.tables.splice(oldIndex, 1)[0];
_this.tables.splice(newIndex, 0, currRow);
}
//保存列表拖拽后顺序
_this.rowSortNew = []; //每次列表拖拽前,清空上次数据
for(let i in _this.tables){//多个对象需遍历赋值
_this.rowSortNew.push(_this.tables[i]['id']);
}
//列表拖拽后顺序
_this.updateTableSort(_this.rowSortNew);
})
},
//列表拖拽后顺序
updateTableSort(rowSortNew){
//控制台输出对比前后顺序
console.log('列表拖拽前顺序id数组:'+this.rowSortOld);
console.log('列表拖拽后顺序id数组:'+rowSortNew);
const formData = new FormData();
//此处封装便于传递给后台
formData.append('rowSortOld',JSON.stringify(this.rowSortOld));
formData.append('rowSortNew',JSON.stringify(rowSortNew));
},
//获取表格渲染数据
getList() {
apiGet(this, this.url).then((res) => {
this.tables = res.data;
//保存列表拖拽前顺序id(注:此ID为列信息中的ID,多个对象需遍历赋值)
for(let i in res.data){
this.rowSortOld.push(res.data[i].id);
}
});
}
}
</script>