最近在使用ant-design-vue做表格時队伟,遇到要做一個可伸縮列表格的需求腔稀,但是官網(wǎng)示例的代碼并不能直接使用盆昙,經(jīng)過一段時間研究以后發(fā)現(xiàn)了可以實現(xiàn)功能的方法。
經(jīng)過嘗試發(fā)現(xiàn)直接修改columns[index].width
可改變表格列的寬度焊虏,這也是最核心的原理淡喜。
之后就需要想辦法實現(xiàn)這個功能,官方示例使用vue-draggable-resizable
來實現(xiàn)拖拽诵闭,那我們就繼續(xù)使用這個插件炼团。
實現(xiàn)過程:
1.查看ant-design-vue中table的api后發(fā)現(xiàn)需要增加components
的配置項
2.查看vue-draggable-resizable
的示例增加拖動組件的配置,并在dragging
事件中設(shè)置表格的寬度
3.動態(tài)創(chuàng)建vue-draggable-resizable
組件
完整示例代碼
<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)
export default {
name: 'App',
data() {
this.components = {
header: {
cell: (h, props, children) => {
const { key, ...restProps } = props
console.log('ResizeableTitle', key)
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, y) => {
col.width = Math.max(x, 1)
}
}
}
const drag = h('vue-draggable-resizable', { ...dragProps })
return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag])
}
}
}
return {
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'
}
],
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' }
}
]
}
}
}
</script>
<style>
.resize-table-th {
position: relative;
}
.table-draggable-handle {
/* width: 10px !important; */
height: 100% !important;
left: auto !important;
right: -5px;
cursor: col-resize;
touch-action: none;
border: none;
}
</style>