vue3 el-table的列拖拽实现(固定最后一列的操作列,不让其与其他列交换位置)

实现这个列拖拽功能,我使用的是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);
      }
    },
  });
};

相关代码就是这些了,若有不对的地方,欢迎指出,更正~

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值