一、需要安装插件Sortable.js
npm i sortablejs --save
或者
yarn add sortablejs --save
二、封装props配置项
export default [
{
width: "auto",
label: "日期",
needSlot: false,
id: "0",
prop: "date",
},
{
width: "auto",
label: "姓名",
needSlot: false,
id: "1",
prop: "name",
},
{
width: "auto",
label: "地址",
needSlot: false,
id: "2",
prop: "address",
},
];
三、引入配置项以及插件
import Sortable from "sortablejs";
// 引入Sortable表格拖拽插件
import schemas from "./schemas";
// 引入配置项
四、el-table渲染相关数据
注意点:
- el-table组件中的data绑定的是接口字段
- el-table-column通过遍历配置项的数据渲染prop,lable, 字段和接口数据需要一一对应,这样就可以实现完成渲染
- 复选框和序号是固定
<template>
<div>
<el-table
:data="tableData"
ref="schema-table"
:key="randomKey"
border
stripe
:row-key="
(row) => {
return row.id;
}
"
>
<!-- 复选框-->
<el-table-column type="selection" width="55" :reserve-selection="true">
</el-table-column>
<el-table-column
label="序号"
type="index"
align="center"
header-align="center"
width="50"
></el-table-column>
<el-table-column
v-for="item in schemas"
:label="item.label"
:key="item.id"
:width="item.width"
:prop="item.prop"
align="center"
header-align="center"
>
<template slot-scope="{ row }">
<span>{{ row[item.prop] }}</span>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from "sortablejs";
// 引入Sortable表格拖拽插件
import schemas from "./schemas";
// 引入mock的数据
export default {
data() {
return {
schemas: schemas,
dateFileds: [],
randomKey: Math.random(),
tableData: [
{
date: "2016-05-02",
name: "王小虎",
id: "0",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-04",
name: "王小虎",
id: "1",
address: "上海市普陀区金沙江路 1517 弄",
},
{
date: "2016-05-01",
name: "王小虎",
id: "2",
address: "上海市普陀区金沙江路 1519 弄",
},
{
date: "2016-05-03",
name: "王小虎",
id: "3",
address: "上海市普陀区金沙江路 1516 弄",
},
],
};
},
watch: {
// 数据发生变化--都需要重新构建sortable
schemas: {
handler(list) {
// list为0 无法拖拽
if (list.length === 0) return;
this.reDrawer();
},
immediate: true,
},
},
async mounted() {
//表格拖拽方法
this.columnDrop();
},
methods: {
/**
* 列拖拽
*/
columnDrop() {
const _this = this;
console.log("数据", this.schemas);
const wrapperTr = document.querySelector(".el-table__header-wrapper tr");
this.sortable = Sortable.create(wrapperTr, {
animation: 180,
delay: 0,
onEnd: (evt) => {
const empty = 2;
// 跳过显示的列数量,如开头我们用了一个多选框,h和序号
const oldItem = this.schemas[evt.oldIndex - empty];
this.schemas.splice(evt.oldIndex - empty, 1);
this.schemas.splice(evt.newIndex - empty, 0, oldItem);
},
});
},
},
/**
* 触发表格重绘
*/
reDrawer() {
this.randomKey = Math.random();
this.$nextTick(() => {
this.columnDrop();
});
},
};
</script>