备注:新版ant-design-vue已增加resizable属性实现此功能,只是我这里升级版本改动太大,所以需要自己写
npm i vue3-draggable-resizable
<template>
<Table
:bordered="true"
:dataSource="dataSource"
:columns="columns"
:components="components"
:scroll="scroll"
/>
</template>
<script lang="ts">
import { Table } from 'ant-design-vue';
import { ref } from 'vue';
import 'ant-design-vue/dist/antd.css';
import { useTableHeadResizable } from './useTableHeadResizable';
const columns = ref([
{
title: '姓名',
dataIndex: 'name',
key: 'name',
width: 100,
},
{
title: '年龄',
dataIndex: 'age',
key: 'age',
width: 100,
},
{
title: '住址',
dataIndex: 'address',
key: 'address',
width: 100,
},
]);
const dataSource = [
{
key: '1',
name: '胡彦斌',
age: 32,
address: '西湖区湖底公园1号',
},
{
key: '2',
name: '胡彦祖',
age: 42,
address: '西湖区湖底公园1号',
},
];
const scroll = {
x: '100%',
};
export default {
components: { Table },
setup() {
return {
columns,
dataSource,
scroll,
components: {
header: {
cell: (columnAttrs, props) =>
useTableHeadResizable(columnAttrs, props, columns),
},
},
};
},
};
</script>
<style>
.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>
// 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';
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 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) => {
columns.value[colIndex].width = Math.max(e.x, 1);
},
};
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],
}
);
};
项目示例:https://stackblitz.com/edit/vue-cef6of?file=src%2FApp.vue