ant design table 表格实现拖拽排序

antd官方文档有支持拖拽的写法,参考地址:https://ant.design/components/table-cn/
根据antd的写法实现了拖拽,但是antd的写法只是实现了功能,对代码没有进行封装,如果你想在多个页面进行拖拽,可能写很多重复代码,所以,本人根据官方文档写法进行了组件化,针对多个页面只需引入即可使用。

1.首先引入支持拖拽的相关插件

 npm install react-dnd --save 
 npm install react-dnd-html5-backend --save
 npm install immutability-helper --save

2.在公共组件目录下新增一个dragTable组件文件,如图:

在这里插入图片描述

3.在dragTable组件中代码如下:

import React, { Component } from 'react';
import { DragSource, DropTarget } from 'react-dnd';

let dragingIndex = -1;

class BodyRow extends React.Component {
  render() {
    const { isOver, connectDragSource, connectDropTarget, moveRow, ...restProps } = this.props;
    const style = { ...restProps.style, cursor: 'move' };

    let className = restProps.className;
    if (isOver) {
      if (restProps.index > dragingIndex) {
        className += ' drop-over-downward';
      }
      if (restProps.index < dragingIndex) {
        className += ' drop-over-upward';
      }
    }

    return connectDragSource(
      connectDropTarget(<tr {...restProps} className={className} style={style} />),
    );
  }
}

const rowSource = {
  beginDrag(props) {
    dragingIndex = props.index;
    return {
      index: props.index,
    };
  },
};

const rowTarget = {
  drop(props, monitor) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;

    // Don't replace items with themselves
    if (dragIndex === hoverIndex) {
      return;
    }

    // Time to actually perform the action
    props.moveRow(dragIndex, hoverIndex);

    // Note: we're mutating the monitor item here!
    // Generally it's better to avoid mutations,
    // but it's good here for the sake of performance
    // to avoid expensive index searches.
    monitor.getItem().index = hoverIndex;
  },
};

export const DragableBodyRow = DropTarget('row', rowTarget, (connect, monitor) => ({
  connectDropTarget: connect.dropTarget(),
  isOver: monitor.isOver(),
}))(
  DragSource('row', rowSource, connect => ({
    connectDragSource: connect.dragSource(),
  }))(BodyRow),
);

4.在使用拖拽的TableComponent组件页引入

import { DragableBodyRow } from '@/components/dragTable.component';
//同时需要引入
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import update from 'immutability-helper';

//在组件TableComponent 加入的方法
 components = {
    body: {
      row: DragableBodyRow,
    },
  };

  moveRow = (dragIndex, hoverIndex) => {
    const { data } = this.state;
    const dragRow = data[dragIndex];
    this.setState(
      update(this.state, {
        data: {
          $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]],
        },
      }),() => {
        console.log(this.state.data)
      }
    );
  };
//在组件TableComponent 的render函数内 ,Table增加两个方法
<Table 
      rowSelection={rowSelection}
      dataSource={this.state.data} 
      columns={columns(this,match.params.id,match.params.name)} 
      rowKey={rowKey}
      pagination={pagination}
      components={this.components}  //此处为拖拽新增的方法1
      onRow={(record, index) => ({     //此处为拖拽新增的方法2
        index,
        moveRow: this.moveRow,
      })}
      loading={loading}
      onChange={this.onTablePageChange}
 />

5.最后在导出时包裹

export default DragDropContext(HTML5Backend)(TableComponent)

6.拖拽过程中加入的样式,放在对应scss文件内,引入即可

tr.drop-over-downward td {
  border-bottom: 2px dashed #1890ff;
}

tr.drop-over-upward td {
  border-top: 2px dashed #1890ff;
}
<think>嗯,用户需要的是如何在AntDesignVue中实现表格拖拽排序的具体方案。用户直接询问了解决方案或示例代码,可见ta正在开发中遇到了技术瓶颈。从用户引用的三篇资料来看,ta已经查阅过相关文档:引用[1]展示了基本的拖拽实现,引用[2]涉及模态框内表格的特殊处理,引用[3]则提到防止列伸缩与排序冲突的技巧——说明用户对技术细节有基本认知,但需要系统化的实现方案。我注意到用户特别强调"不是真正需求",说明ta可能被杂乱的技术博客困扰过。实际上核心需求很明确:既要实现drag&drop交互,又要保持AntDesign的表格特性。其中三个技术要点需要突出:1)行拖拽必须与sortable.js深度整合,这在用户提供的代码片段中已见端倪2)模态框内的z-index问题容易被忽略(引用[2]的forceRender就是伏笔)3)拖拽过程中的数据同步是关键难点,需要避免直接操作DOM用户没有说明使用Vue2还是Vue3,稳妥起见应当提供兼容方案。考虑到ta引用中多次出现vue2语法,重点给出vue2方案。另外ta特别关注动画效果,响应时需补充CSS过渡部分。技术实现上要避开两个坑:一是AntDesign的rowKey必须设置,否则拖拽后会出现数据错位;二是移动端支持需要额外处理touch事件,不过用户没提就不展开。最后示例代码应当保留TS类型提示,虽然用户没要求,但企业级项目通常需要类型安全。</think> 根据引用内容,Ant Design Vue 实现表格拖拽排序的核心方案如下(附完整示例): ```vue <template> <a-table :columns="columns" :data-source="dataSource" :components="components" rowKey="id" :customRow="customRow" > <!-- 拖拽手柄列 --> <template #handle> <DragOutlined style="cursor: move" /> </template> </a-table> </template> <script> import { DragOutlined } from '@ant-design/icons-vue'; import Sortable from 'sortablejs'; export default { components: { DragOutlined }, data() { return { dataSource: [...], // 表格数据 columns: [ { title: '排序', dataIndex: 'sort', width: 80, slots: { customRender: 'handle' } // 拖拽手柄列 }, // 其他业务列... ], components: { body: { wrapper: this.dragWrapper, // 拖拽容器组件 row: this.dragRow // 拖拽行组件 } } }; }, mounted() { this.initSortable(); }, methods: { // 初始化拖拽功能 initSortable() { const table = this.$el.querySelector('.ant-table-tbody'); this.sortable = Sortable.create(table, { animation: 150, handle: '.anticon-drag', onEnd: this.onSortEnd }); }, // 拖拽结束回调 onSortEnd({ oldIndex, newIndex }) { const dataSource = [...this.dataSource]; const movedItem = dataSource.splice(oldIndex, 1)[0]; dataSource.splice(newIndex, 0, movedItem); this.dataSource = dataSource.map((item, index) => ({ ...item, sort: index + 1 // 更新排序序号 })); // 此处可提交排序结果到后端 [^3] }, // 自定义行属性 customRow() { return { class: 'drag-row', // 拖拽行样式 attrs: { draggable: true } // 启用拖拽 }; }, // 拖拽容器包裹组件 [^1][^3] dragWrapper(props) { return <tbody {...props} />; }, // 拖拽行组件 dragRow(props) { return <tr {...props} />; } } }; </script> <style> .drag-row { transition: all 0.3s; /* 添加过渡动画 */ } </style> ``` ### 关键实现要点: 1. **依赖库**:使用 `sortablejs` 库实现拖拽核心功能 [^1][^2] 2. **图标手柄**:通过插槽添加拖拽图标(如`<DragOutlined />`) 3. **挂载时机**:在 `mounted` 生命周期初始化拖拽实例 4. **数据处理**: - 拖拽结束后更新数据源顺序 - 通过 `splice` 重新排序数组 - 更新每行的排序序号字段 [^2] 5. **动画效果**: - 使用 CSS 过渡动画(`transition: all 0.3s`) - 依赖 `Sortable.create` 的 animation 参数 ### 注意事项: 1. **必须设置 `rowKey`**:确保每行有唯一标识(如`id`字段)[^3] 2. **模态框处理**:模态框内表格需添加 `forceRender=true` 避免渲染问题 [^2] 3. **冲突解决**:同时实现伸缩列时需阻止拖动事件冒泡 [^3] > 实际项目中建议将拖拽逻辑封装为可复用mixin或自定义hook,参考示例可在Ant Design Vue官方示例库中找到 [^1][^3]。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值