vben admin Table 实现表格列宽自由拖拽

本文介绍了如何在Vue3项目中使用`vue3-draggable-resizable`库实现ant-design-vue2表格列的拖拽效果,以及遇到的不流畅问题和解决方法,包括禁用排序事件触发和使用鼠标右键拖动等技巧。
摘要由CSDN通过智能技术生成

参考:

Vue3+ant-design-vue2实现table列拖拽效果不够丝滑BUG_antdv table vuedraggableresizable 拖拽不流畅-CSDN博客

第一步:

引入包:

pnpm i vue3-draggable-resizable

第二步:在列表中插入useTableHeadResizable.ts文件

import { h } from 'vue';
import VueDraggableResizable from 'vue3-draggable-resizable';
import { DraggableContainer } from 'vue3-draggable-resizable';
import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css';
import { useThrottleFn } from '@vueuse/core';

export const useTableHeadResizable = (columnAttrs, props, columns) => {
  const { key } = columnAttrs;
  const { children } = props[0];

  const colIndex = columns.value.findIndex((col) => {
    const k = col.key || col.dataIndex;
    return k === key;
  });
  if (!columns.value[colIndex] || !columns.value[colIndex].width) {
    return h('th', { ...columnAttrs }, [children]);
  }

  const throttledFn = useThrottleFn((columns, colIndex, x) => {
    console.log(columns);
    columns[colIndex].width = Math.max(x, 50);
  }, 100);

  const dragProps = {
    key: columns.value[colIndex].dataIndex || columns.value[colIndex].key,
    class: 'table-draggable-handle',
    w: 5,
    x: columns.value[colIndex].width,
    disabledY: true,
    draggable: true,
    resizable: false,
    onDragging: (e) => {
      throttledFn(columns.value, colIndex, e.x);
    },
  };

  const resizable = h(VueDraggableResizable, { ...dragProps });
  const container = h(
    DraggableContainer,
    { disabled: true, style: 'position: unset' },
    { default: () => resizable },
  );

  return h(
    'th',
    { ...columnAttrs, class: 'resize-table-th' },
    {
      default: () => [children, container],
    },
  );
};

第三步:找到Table组件中的useColumns.ts文件,将columnsRef抛出

第4步:在BasicTable组件中,引入第二步的文件,并配置在表格头的cell中

import { useTableHeadResizable } from './useTableHeadResizable';

在此文件中不要忘了加上style样式

<style lang="less">
.table-draggable-handle {
  height: 50px !important;
  left: auto !important;
  right: -5px;
  cursor: col-resize;
  touch-action: none;
  border: none;
  position: absolute;
  transform: none !important;
  bottom: 0;
  border: none !important;
}
.resize-table-th {
  position: relative;
}
.ant-table-column-sorters {
  display: table;
}
</style>

另:仅有当column项的宽设了值后,才可以拖动宽的长短。 例:

 {
    title: '类别',
    dataIndex: 'deviceType',
    width: 100,
    sorter: true,
 }

最后TIPS:样式生效,但是如果表格列有排序,排序的触发事件放在表头的,所以拖动会触发本列的排序事件。

解决方式:

一就是用鼠标右键进行拖动,避免触发click。

二就是将排序的触发事件绑定在排序icon上。

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值