Vue2官方地址
官方给的地址表头数据、表格和ResizeableTitle都是写在外面的,不好用。
这里给一个经过请求获取表格数据之后在伸缩的写法
<template>
<div>
测试表格
<a-table
bordered
:columns="headerData"
:components="components"
:data-source="tableData"
>
</a-table>
</div>
</template>
<script>
export default {
data() {
return {
headerData: [],
tableData: [],
components: {},
};
},
props: [
],
created() {
this.init();
//2.把getTitle函数拆开放在这里,也没有作用
this.getTitle(this.headerData);//3.只有封装成函数才有用
},
methods: {
init() {
Object.assign(newParams, this.tbHeaderParams, params);
this.$api.发请求.then(({ data }) => {
data.map((v) => {
this.headerData.push({
title: "-----",
dataIndex: "-----",
key: "-----",
width: 100,
});
});
//1.把getTitle函数拆开放在这里,没有作用
});
},
getTitle(columns) {
const draggingMap = {};
columns.forEach((col) => {
draggingMap[col.key] = col.width; //添加键值对,有key的才添加
});
const resizeableTitle = (h, props, children) => {
let thDom = null;
const { key, ...restProps } = props;
const col = columns.find((col) => {
const k = col.dataIndex || col.key;
return k === key;
});
if (!col.width) {
return <th {...restProps}>{children}--</th>;
}
const onDrag = (x) => {
draggingMap[key] = 0;
col.width = Math.max(x, 1);
};
const onDragstop = () => {
draggingMap[key] = thDom.getBoundingClientRect().width;
};
return (
<th
{...restProps}
v-ant-ref={(r) => (thDom = r)}
width={col.width}
class="resize-table-th"
>
{children}
<vue-draggable-resizable
key={col.key}
class="table-draggable-handle"
w={10}
x={col.width}
z={1}
axis="x"
draggable={true}
resizable={false}
onDragging={onDrag}
onDragstop={onDragstop}
></vue-draggable-resizable>
</th>
);
};
this.components = {
header: {
cell: resizeableTitle,
},
};
},
},
};
</script>
<style>
.resize-table-th {
position: relative;
}
.resize-table-th .table-draggable-handle {
height: 100% !important;
bottom: 0;
/* left: auto !important; */
/* right: -5px; */
left: 0;
cursor: col-resize;
/* touch-action: none; */
position: absolute;
background-color: pink;
}
</style>
原理是把获取ResizeableTitle的过程提取出一个函数,在created生命周期获取表头数据的之后在调用,注意要封装成函数,分开好像没效果
注意:
1.表头的数据中需要有width
2.官网给的ResizeableTitle会报错,改成小写的resizeableTitle
3.const draggingState = Vue.observable(draggingMap);这行可以不需要,直接用draggingMap
4.下面的代码不必在当前vue文件中写,可以注册成全局组件,也是可以的
import Vue from 'vue';
import VueDraggableResizable from 'vue-draggable-resizable';
Vue.component('vue-draggable-resizable', VueDraggableResizable);
5.components自己写
效果图
点击粉色位置即可伸缩表头列