实现这个列拖拽功能,我使用的是sortable.js 插件
需要先进行安装:
npm install sortablejs --save
//这是 template结构 table组件 代码
<el-table
class="drag_box" //注意要给table起个类名,用于拖拽方法里 获取tr元素的
ref="tableRef"
:data="getList"
style="width: 100%"
border
stripe
:show-overflow-tooltip="true"
column-key="id"
>
<!-- 根据dragCols的顺序生成列 -->
<el-table-column
v-for="(item, index) in dragCols"
:key="item.prop"
:prop="item.prop"
:label="item.label"
:resizable="item.resizable" //定义可拉伸
:width="item.width" //自定义列宽度
:fixed="item.fixed" //固定列
:draggable="true"
>
.......内容省略......
</el-table-column>
</el-table>
// 与表格相关的逻辑代码
import Sortable from "sortablejs";
//定义好dragCols数组,用于上面的v-for循环表格列
const dragCols = ref([
{ label: "订单编号", prop: "id", resizable: true, width: 180 },
{
label: "政策代码",
prop: "policy_code",
resizable: true,
width: 300,
},
{ label: "PNR", prop: "pnr", resizable: true },
{ label: "时间", prop: "create_time", resizable: true, width: 200 },
{ label: "乘机人", prop: "passengers", resizable: true, width: 220 },
{ label: "航班信息", prop: "flights", resizable: true, width: 400 },
{ label: "操作", prop: "action", fixed: "right" },
]);
// 2. 设置列拖拽
const columnDrop = () => {
// 获取元素
const tr = document.querySelector(".drag_box .el-table__header-wrapper tr");
Sortable.create(tr as HTMLElement, {
animation: 180,
delay: 0,
filter: `.el-table_1_column_${dragCols.value.length}`,
// ↑↑↑↑↑ 过滤不需要拖拽的元素,我使用的是元素类名,这是我的最后一列
onEnd: (e) => {
const oldIndex = e.oldIndex;
const newIndex = e.newIndex;
const lastColumnIndex = dragCols.value.length - 1;
if (newIndex === lastColumnIndex) {
// 如果拖动的列移动到了最后一列的位置,则将其还原到原来的位置
tr!.insertBefore(e.item, tr!.children[oldIndex!]);
} else {
// 其他情况下,更新列的位置
const oldColumn = dragCols.value[oldIndex!];
dragCols.value.splice(oldIndex!, 1);
dragCols.value.splice(newIndex!, 0, oldColumn);
}
},
});
};
相关代码就是这些了,若有不对的地方,欢迎指出,更正~