最近在用ant-design-vue
開發(fā)項(xiàng)目時(shí)遇到一個(gè)表格列需要支持拖拽改變寬度达箍,這個(gè)功能在element-ui
上直接可以使用晰搀,但ant-design-vue
需要引用一個(gè)叫vue-draggable-resizable
的插件才能實(shí)現(xiàn)会前,本以為很簡(jiǎn)單照著官網(wǎng)寫即可左敌,沒想到官網(wǎng)的demo在本地一直報(bào)錯(cuò):
image.png
網(wǎng)上搜了一大堆也沒有解決忌警,最終在github
上找到了一個(gè)解決方案,官網(wǎng)的實(shí)例可以復(fù)制過來使用掺炭,但需要進(jìn)行改造:
ResizeableTitle報(bào)錯(cuò)問題:ResizeableTitle 改成 resizeableTitle;
表格沒有拖動(dòng)滑塊樣式問題:.table-draggable-handle 里加上 transform: none !important; position: absolute;
去掉style的scoped屬性;
動(dòng)態(tài)表頭無(wú)法拖動(dòng)問題:將columns定義在data中不要放在computed里
完整代碼如下:
<template>
<a-table
bordered
:columns="columns"
:components="components"
:data-source="data"
>
<template v-slot:action>
<a href="javascript:;">Delete</a>
</template>
</a-table>
</template>
<script>
import Vue from "vue";
import VueDraggableResizable from "vue-draggable-resizable";
Vue.component("vue-draggable-resizable", VueDraggableResizable);
const columns = [
{
title: "Date",
dataIndex: "date",
width: 200,
},
{
title: "Amount",
dataIndex: "amount",
width: 100,
},
{
title: "Type",
dataIndex: "type",
width: 100,
},
{
title: "Note",
dataIndex: "note",
width: 100,
},
{
title: "Action",
key: "action",
scopedSlots: { customRender: "action" },
},
];
const 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",
},
];
const draggingMap = {};
columns.forEach((col) => {
draggingMap[col.key] = col.width;
});
const draggingState = Vue.observable(draggingMap);
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) => {
draggingState[key] = 0;
col.width = Math.max(x, 1);
};
const onDragstop = () => {
draggingState[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={draggingState[key] || col.width}
z={1}
axis="x"
draggable={true}
resizable={false}
onDragging={onDrag}
onDragstop={onDragstop}
></vue-draggable-resizable>
</th>
);
};
export default {
name: "App",
data() {
this.components = {
header: {
cell: resizeableTitle,
},
};
return {
data,
columns,
};
},
};
</script>
<style lang="less">
.resize-table-th {
position: relative;
.table-draggable-handle {
transform: none !important;
position: absolute;
height: 100% !important;
bottom: 0;
left: auto !important;
right: -5px;
cursor: col-resize;
touch-action: none;
}
}
</style>