1、安装vue-draggable-resizable

npm install vue-draggable-resizable

2、在main.js中引入vue-draggable-resizable

// 全局引入antd table 拖动列宽插件
import VueDraggableResizable from 'vue-draggable-resizable'
import 'vue-draggable-resizable/dist/VueDraggableResizable.css'
Vue.component('vue-draggable-resizable', VueDraggableResizable)

import '@assets/less/draggable-resizable.less';

3、src/utils下在封装组件draggable-resizable.js

export const dragResizableFunc = columns => {
  let column = {
    header: {
      cell: (h, props, children) => {
        const { key, ...restProps } = props
        const col = 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,
            transform: 'none',
            resizable: false
          },
          on: {
            dragging: x => {
              col.width = Math.max(x, 120)
            }
          }
        }
        // console.log(dragProps,'dragProps')
        const drag = h('vue-draggable-resizable', { ...dragProps })
        // console.log(drag,'drag')
        return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag])
      }
    }
  }
  // console.log(column,'column-------------0000000000')
  return column
}


4、在ant design vue table中使用

// 引入调整列宽js
import { dragResizableFunc } from '@/utils/draggable-resizable'

<a-table
    ref="table"
    size="middle"
    rowKey="id"
    :columns="columns"
    :dataSource="dataSource"
    :pagination="ipagination"
    :loading="loading"
    class="j-table-force-nowrap"
    @change="handleTableChange"
    :scroll='{x:screenW}'
    :bordered='bordered'
    :components="componentsChange(columns)"
>
</a-table>

// 拖动列宽
componentsChange(columns){
    return dragResizableFunc(columns)
},

注意点:
1、列伸缩有两个属性,width和dataIndex必有属性,且width必须为数值,不能为百分比。
2、如果table的表头存在动态表头的情况下,就会对列拖拽功能有影响,存在失灵情况,此时需要特殊处理。需要给table加上v-if判断

更多推荐