<template>
<!-- 外层套一个固定宽度的div是为了看看当table拉伸超过父组件时是什么效果 -->
<div class="parentContainer">
<a-table
bordered
:columns="columns"
:data-source="data"
:components="components"
>
</a-table>
</div>
</template>
<!-- eslint-disable -->
<script>
import Vue from "vue";
import VueDraggableResizable from "vue-draggable-resizable";
Vue.component("vue-draggable-resizable", VueDraggableResizable);
export default {
data() {
this.components = {
header: {
cell: (h, props, children) => {
// console.log("h:", h);
// console.log("props:", props);
// console.log("children:", children);
const { key, ...restProps } = props;
const col = this.columns.find((col) => {
const k = col.dataIndex || col.key;
return k === key;
});
if (!col || !col.width) {
return h("th", { ...restProps }, [...children]);
}
const dragProps = {
key: col.dataIndex || col.key,
class: "table-draggable-handle", // 拖拽句柄的样式
attrs: {
w: 10,
x: col.width,
z: 1,
axis: "x",
draggable: true,
resizable: false,
},
on: {
dragging: (x) => {
col.width = Math.max(x, 1);
},
},
};
const drag = h("vue-draggable-resizable", { ...dragProps });
return h("th", { ...restProps, class: "resize-table-th" }, [
...children,
drag,
]);
},
},
};
return {
columns: [],
data: [],
};
},
mounted() {
this.initHandler();
},
methods: {
initHandler() {
this.columns = [
{
title: "日期",
dataIndex: "date",
width: 100, // 要有width
},
{
title: "分类",
dataIndex: "type",
width: 100, // 要有width
},
{
title: "金额",
dataIndex: "amount",
width: 100, // 要有width
},
{
title: "备注",
dataIndex: "note",
width: 100, // 要有width
},
{
title: "操作",
dataIndex: "action",
width: 100, // 要有width
scopedSlots: { customRender: "action" },
},
];
this.data = [
{
key: 0,
date: "2018-02-11",
amount: 120,
type: "income",
note: "transfer",
},
{
key: 1,
date: "2018-03-11",
amount: 243,
type: "income",
note: "transfer",
},
{
key: 2,
date: "2018-04-11",
amount: 98,
type: "income",
note: "transfer",
},
];
},
},
};
</script>
<!-- 注意 无scope -->
<style lang="less" >
.parentContainer {
margin-left: 60px;
width: 900px;
background-color: yellow; // 放开注释可以用来观察效果,实际使用时可以注释此行
}
// 拖拽句柄的样式
.table-draggable-handle {
background-color: red; // 放开注释可以用来观察效果,实际使用时可以注释此行
height: 100% !important;
left: auto !important;
right: -5px; // 偏移量
cursor: col-resize;
touch-action: none;
border: none;
position: absolute;
transform: none !important;
bottom: 0;
}
.resize-table-th {
position: relative;
}
</style>
官网的例子有问题。
借鉴了博客上别人的代码,加以修改和注释。大家直接粘贴运行即可。
使用场景:columns动态生成的时候。