Element ui表格行、列拖拽
Element ui表格行、列拖拽
·
1、首先安装vuedraggable插件或直接安装sortablejs
npm i -S vuedraggable
npm i sortablejs --save
2、更多属性配置参考中文文档:vue.draggable中文文档 - itxst.com
3、在需要配置的页面引入
import Sortable from 'sortablejs';
4、要点:
4.1、先找到拖拽元素的父容器
4.2、行拖拽:在 el-table 标签中,根据行的内容指定行的唯一标识 row-key="id"
4.3、列拖拽:额外定义两个数组,分别存储拖拽前的列顺序和拖拽后的列顺序
完整代码
<template>
<div class="draggable" style="padding: 20px">
<el-table
row-key="id"
:data="dataList"
style="width: 100%"
border
>
<el-table-column
v-for="(item,index) in oldList"
:key="`col_${index}`"
:prop="newList[index].prop"
:label="item.label"
align="center"
>
</el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs';
export default {
mounted() {
this.oldList = JSON.parse(JSON.stringify(this.tableConfig.tableItems))
this.newList = JSON.parse(JSON.stringify(this.tableConfig.tableItems))
this.columnDrop()
this.rowDrop()
},
data() {
return {
oldList: [],
newList: [],
dataList: [
{
id:1,
name:'温度',
type:'℃',
value:10,
},
{
id:2,
name:'PM2.5',
type:'ug/m3',
value:20,
},
{
id:3,
name:'PM10',
type:'ug/m3',
value:30,
},
],
tableConfig: {
tableItems: [
{
label: '名称',
prop: 'name',
},
{
label: '类型',
prop: 'type',
},
{
label: '值',
prop: 'value',
}
]
}
}
},
methods: {
// 行拖拽
rowDrop() {
// 此时找到的元素是要拖拽元素的父容器
const tbody = document.querySelector('.draggable .el-table__body-wrapper tbody');
const _this = this;
Sortable.create(tbody, {
// 指定父元素下可被拖拽的子元素
draggable: ".draggable .el-table__row",
onEnd({newIndex, oldIndex}) {
const currRow = _this.dataList.splice(oldIndex, 1)[0];
_this.dataList.splice(newIndex, 0, currRow);
}
});
},
// 列拖拽
columnDrop() {
const wrapperTr = document.querySelector('.draggable .el-table__header-wrapper tr');
this.sortable = Sortable.create(wrapperTr, {
animation: 180,
delay: 0,
onEnd: evt => {
const oldItem = this.newList[evt.oldIndex];
this.newList.splice(evt.oldIndex, 1);
this.newList.splice(evt.newIndex, 0, oldItem);
}
});
}
}
}
</script>
<style scoped>
</style>
更多推荐
已为社区贡献8条内容
所有评论(0)