vue + antdesign使用vue-draggable-resizable实现表格列拖拽

文章介绍了如何在AntDesign1.x版本的表格中实现列宽的自定义拖拽功能,由于该版本不支持此特性,作者利用vue-draggable-resizable插件进行集成实现。主要步骤包括安装插件、引入并注册组件、在table组件中配置components属性以及定义相关数据和样式。

需求: 表格列太多,想要自定义拖拽宽度。antdesign 3.0+版本table自带伸缩列的功能,但我项目中用的是1.0+版本,所以只有结合vue-draggable-resizable拖拽插件来实现了

效果图:

vue-draggable-resizab表格列自定义拖拽

实现代码:
1.下载插件依赖

npm install --save vue-draggable-resizable

2.在main.js中引入插件

import VueDraggableResizable from 'vue-draggable-resizable'
Vue.component('vue-draggable-resizable', VueDraggableResizable)

3.在使用页面中重新引入插件

import VueDraggableResizable from 'vue-draggable-resizable'

4.在table 组件中添加components属性

<a-table
        bordered
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pagination="pagination"
        :rowKey="(record,index)=>{return index}"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
        :scroll="{x:'max-content',y:540}"
        :components='components'>
</a-table>

5.在data中定义components属性代码(columns每一列都要设置width,如果不设置width属性,拖动时不生效)

<script>
import VueDraggableResizable from 'vue-draggable-resizable'

export default {
components: {
    VueDraggableResizable
  },
  data() {
    this.components = {
      header: {
        cell: (h, props, children) => {
          const { key, ...restProps } = props
          // 此处的this.columns 是定义的table的表头属性变量
          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 {
      columns:[
        {
          title: '商品名称',
          dataIndex: 'goods_name',
          width: 150,
          // ellipsis: true 不要加这个属性,不然拖拽到最小宽度时,表头和表格会发生错位
        },
        {
          title: '商品编号',
          dataIndex: 'spec_code',
          width: 120,
          scopedSlots: { customRender: 'specCode' }
        },
        {
          title: '规格型号',
          dataIndex: 'spec_name',
          width: 100,
          scopedSlots: { customRender: 'specName' }
        },
        {
          title: '单位',
          dataIndex: 'goods_unit_name',
          width: 100,
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 120,
          customRender: (text, row, index) => {
            if (text == '1') {
              return '有效'
            } else {
              return '失效'
            }
          }
        },
        {
          title: '分类',
          dataIndex: 'gc_name',
          width: 200,
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 180,
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  }
}
</script>

6.添加style样式(style不能添加scoped属性)

<style>
	.table-draggable-handle {
	  height: 100% !important;
	  left: auto !important;
	  right: -5px;
	  cursor: col-resize;
	  touch-action: none;
	  border: none;
	  position: absolute;
	  transform: none !important;
	  bottom: 0;
	}
	.resize-table-th {
	  position: relative;
	}
</style>

完整代码:

<template>
	<a-table
        bordered
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pagination="pagination"
        :rowKey="(record,index)=>{return index}"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange"
        :scroll="{x:'max-content',y:540}"
        :components='components'>
</a-table>
</template>
 
<script>
import VueDraggableResizable from 'vue-draggable-resizable'
 
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 {
      columns:[
        {
          title: '商品名称',
          dataIndex: 'goods_name',
          width: 150,
        },
        {
          title: '商品编号',
          dataIndex: 'spec_code',
          width: 120,
          scopedSlots: { customRender: 'specCode' }
        },
        {
          title: '规格型号',
          dataIndex: 'spec_name',
          width: 100,
          scopedSlots: { customRender: 'specName' }
        },
        {
          title: '单位',
          dataIndex: 'goods_unit_name',
          width: 100,
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 120,
          customRender: (text, row, index) => {
            if (text == '1') {
              return '有效'
            } else {
              return '失效'
            }
          }
        },
        {
          title: '分类',
          dataIndex: 'gc_name',
          width: 200,
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 180,
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  }
}
</script>
 
<style>
	.table-draggable-handle {
	  height: 100% !important;
	  left: auto !important;
	  right: -5px;
	  cursor: col-resize;
	  touch-action: none;
	  border: none;
	  position: absolute;
	  transform: none !important;
	  bottom: 0;
	}
	.resize-table-th {
	  position: relative;
	}
</style>

### 解决 Ant Design Vue使用 `vue-draggable-resizable` 导致固定多出空白的问题 当在 Ant Design Vue表格中应用 `vue-draggable-resizable` 实现拖拽功能时,可能会遇到固定(fixed columns)出现问题的情况。具体表现为,在调整某些度之后,会出现额外的空白或布局错乱的现象。 #### 原因分析 此现象的主要原因在于 `vue-draggable-resizable` 修改了表头单元格的度属性,而这些变化并未同步到对应的主体部分以及固定上。由于 Ant Design Vue 表格组件内部对于固定有特殊的渲染逻辑,这可能导致视觉上的重复效果[^3]。 #### 解决策略 为了有效处理上述问题,可以采取以下措施: 1. **监听并更新度** 动态监控每表头的实际度,并将其应用于对应的数据行中的单元格。可以通过事件绑定的方式获取每次拖动结束后的最终尺寸值。 2. **强制刷新表格结构** 当检测到任何一被重新设置了度后,调用表格实例的方法来触发一次完整的重绘过程,从而确保所有元素的位置关系得到及时修正。 3. **CSS 调整** 针对可能出现的样式冲突情况,适当修改 CSS 样式定义,特别是涉及到定位和溢出控制的部分,以防止不必要的滚动条或其他异常表现形式出现。 4. **补丁脚本** 下面是一个简单的 JavaScript 函数片段用于辅助完成以上操作: ```javascript // 定义一个方法用来同步 function syncColumnWidths() { const headers = document.querySelectorAll('.ant-table-thead th'); Array.from(headers).forEach((header, index) => { let width = header.offsetWidth; // 更新相应数据行内相同索引位置td标签style里的width属性 document.querySelectorAll(`.ant-table-tbody td:nth-child(${index + 1})`).forEach(td => { td.style.width = `${width}px`; }); // 如果存在固定的左侧/右侧,则同样需要更新它们各自的子元素 ['left', 'right'].forEach(fixedDirection => { document.querySelectorAll( `.ant-table-body-${fixedDirection} .ant-table-fixed-${fixedDirection} table tbody tr td:nth-child(${index + 1})` ).forEach(td => { td.style.width = `${width}px`; }); }); }); } // 给每一个可调节大小的手柄添加dragstop事件处理器 document.querySelectorAll('.table-draggable-handle').forEach(handle => { handle.addEventListener('dragend', () => setTimeout(syncColumnWidths)); }); ``` 这段代码实现了每当用户停止拉动某个手柄时就会自动执行一次同步动作,以此保持整个表格的一致性和美观度[^2]。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值