参考:
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上。