antdesign表格使用Sortable进行行列拖拽

本文介绍了如何在AntDesign Vue的表格组件中利用SortableJS实现行列的拖拽功能,详细讲解了配置过程和关键代码,帮助开发者提升前端交互体验。
<template>
  <a-table :columns="columns" :data-source="dataSource" bordered></a-table>
</template>
<script>
import Sortable from 'sortablejs'
import { defineComponent, onMounted, ref } from 'vue';
import { message } from 'ant-design-vue';

const data = [];
for (let i = 0; i < 100; i++) {
  data.push({
    key: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`,
    operation: i
  });
}
export default defineComponent({
  setup() {
    const columns = ref([{
      title: 'name',
      dataIndex: 'name',
      width: '25%',
    }, {
      title: 'age',
      dataIndex: 'age',
      width: '15%',
    }, {
      title: 'address',
      dataIndex: 'address',
      width: '40%',
    }, {
      title: 'operation',
      dataIndex: 'operation',
    }]);
    const dataSource = ref(data);
    onMounted(() => {
      columnDrop();
      rowDrop();
    })
    const columnDrop = () => {
      const wrapperTr = document.querySelector('.ant-table-thead tr');
      Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        // onEnd: evt => {
        //   const oldItem = columns.value[evt.oldIndex]
        //   columns.value.splice(evt.oldIndex, 1)
        //   columns.value.splice(evt.newIndex, 0, oldItem)
        // }
        onEnd: evt => {
          const oldItem = columns.value[evt.oldIndex];
          columns.value.splice(evt.oldIndex, 1);
          columns.value.splice(evt.newIndex, 0, oldItem);
          // 不能跟第一列置换位置
          if (evt.newIndex == 0) {
            message.info('不能跟第一列置换位置。')
            const oldItem = columns.value[evt.newIndex];
            columns.value.splice(evt.newIndex, 1);
            columns.value.splice(evt.oldIndex, 0, oldItem);
            // 复原拖拽之前的 dom
            const tagName = evt.item.tagName;
            const items = evt.from.getElementsByTagName(tagName);
            if (evt.oldIndex > evt.newIndex) {
              evt.from.insertBefore(evt.item, items[evt.oldIndex + 1]);
            } else {
              evt.from.insertBefore(evt.item, items[evt.oldIndex]);
            }
          }
        }
      })
    }

    const rowDrop = () => {
      const wrapperTr = document.querySelector('.ant-table-tbody');
      Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: evt => {
          const currRow = dataSource.value.splice(evt.oldIndex, 1)[0];
          dataSource.value.splice(evt.newIndex, 0, currRow);
        }
      })
    }
    return {
      dataSource,
      columns,
    };
  },
});
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
<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]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值