The content in the table is too long and is hidden. I want to change the column width by dragging to display the content in the table.
The code is implemented as follows:
1. Add dependencies
Download plug-in dependencies:
npm install --save vue-draggable-resizable
Introduce plugin:
<script> import Vue from 'vue' import VueDraggableResizable from 'vue-draggable-resizable' Vue.component('vue-draggable-resizable', VueDraggableResizable) </script>
2. Add bordered and components attributes to the table component
<template> <a-table bordered :columns="columns" :components="components" :data-source="list"> <template v-slot:action> <a href="javascript:;">Delete</a> </template> </a-table> </template>
3. Define components attribute code in data
Note: Width and (dataIndex/key) must be set for each column of columns. If the width attribute is not set, it will not take effect when dragging.
Note: Do not add the ellipsis attribute to columns, otherwise the header and table will be misaligned when dragged to the minimum width.
<script> export default {<!-- --> components: {<!-- --> VueDraggableResizable }, data() {<!-- --> this.components = {<!-- --> header: {<!-- --> cell: (h, props, 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, 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 {<!-- --> list:[], 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', width: 120, scopedSlots: {<!-- --> customRender: 'action' } } ] } } } </script>
4. Add style
Note: style cannot add scoped attribute
Note: Add transform: none !important; position: absolute; to table-draggable-handle;
Note: Add position: relative; to resize-table-th;
<style lang="less"> .table-draggable-handle {<!-- --> transform: none !important; position: absolute; height: 100% !important; left: auto !important; right: -5px; cursor: col-resize; touch-action: none; bottom: 0; } .resize-table-th {<!-- --> position: relative; } </style>
Final code:
<template> <a-table bordered :columns="columns" :components="components" :data-source="list"> <template v-slot:action> <a href="javascript:;">Delete</a> </template> </a-table> </template>