支持行拖动,列拖动
插件:sortablejs
UI: elementUI
<template>
<div>
<hr style="margin: 30px 0;">
<div>
<!-- 数据里面要有主键id, 否则拖拽异常 -->
<h2 style="margin-bottom: 30px">【sortablejs】实现行拖拽和列拖拽</h2>
<el-table :data="tableData" row-key="id" border style="width: 50%">
<el-table-column
v-for="(item, index) in colList"
align="center"
show-overflow-tooltip
:key="`col_${index+1}`"
:prop="dropCol[index].prop"
:label="item.label"
:min-width="item.minWidth"
:class-name="item.className"
:fixed="item.fixed"
>
<template v-if="item.prop =='setting'">
<slot :name="item.prop" slot-scope="scope">
<!-- 加上这列,如果不固定到右侧,会使得列拖拽异常 -->
<!-- 右侧固定列不动 应该有特殊写法 -->
<el-button size="mini">编辑{{scope.setting}}</el-button>
</slot>
</template>
</el-table-column>
</el-table>
</div>
</div>
</template>
<script>
import draggable from "vuedraggable";
import Sortable from "sortablejs";
import { mapState } from 'vuex';
export default {
components: {
draggable,
},
data() {
return {
dropCol: [
{
label:'日期',
prop: 'date'
},
{
label:'姓名',
prop:'name'
},
{
label:'地址',
prop: 'address'
},
{
label:'操作',
prop: 'setting',
width: 120
}
],
colList: [//多写了一个,和上面dropCol相同,为了防止列拖拽时数据不跟随
{
label:'日期',
prop: 'date'
},
{
label:'姓名',
prop:'name'
},
{
label:'地址',
prop: 'address'
},
{
label:'操作',
prop: 'setting',
width: 120,
className: 'disabled',
fixed: 'right'//固定到右侧,否则列拖拽异常
}
],
tableData: [
{
date: "2016-05-03",
name: "A",
address: "No. 189, Grove St, Los Angeles",
id: 1,
setting: 'setting1'
},
{
date: "2016-05-02",
name: "B",
address: "No. 189, Grove St, Los Angeles",
id: 2,
setting: 'setting2'
},
{
date: "2016-05-04",
name: "C",
address: "No. 189, Grove St, Los Angeles",
id: 3,
setting: 'setting3'
},
{
date: "2016-05-01",
name: "D",
address: "No. 189, Grove St, Los Angeles",
id: 4,
setting: 'setting4'
},
],
};
},
mounted(){
this.rowDrop()
this.columnDrop()
},
methods: {
rowDrop(){//行拖拽
const tbody = document.querySelector('.el-table__body-wrapper tbody');
const _this = this;
Sortable.create(tbody,{
animation: 180,
delay: 0,
onEnd({ newIndex, oldIndex }){
const currRow = _this.tableData.splice(oldIndex, 1)[0];
console.log(currRow,currRow.name)
_this.tableData.splice(newIndex, 0, currRow)
console.log('_this.tableData',_this.tableData)
}
})
},
columnDrop(){//列拖拽
const theader = document.querySelector('.el-table__header-wrapper tr');
this.sortable = Sortable.create(theader,{
animation: 180,
filter: '.disabled',
onEnd: e=> {
const oldItem = this.dropCol[e.oldIndex];
this.dropCol.splice(e.oldIndex, 1);
this.dropCol.splice(e.newIndex, 0, oldItem)
}
})
}
},
};
</script>
<style lang="less" scoped>
.drag-resize{
height: 400px;
width: 100%;
background: rgb(196, 196, 139);
border: 1px solid #888;
border-radius: 2px;
position: relative;//不设置这个,被拖拽的元素就跑外面去了
}
.drag-element-seat{
width: 100%;
height: 100%;
}
</style>