vue 基于antd的a-table实现列表可拖拽行排序

1,127 阅读1分钟

列表配置

<a-table
    class="ant-table-striped"
    size="middle"
    bordered
    :pagination="false"
    :columns="columns"
    :data-source="listData"
    :loading="loadingTable"
    :scroll="{ x: 328 }"
    :customRow="customRow"
    >
                       
 </a-table>

主要是配置customRow

用钩子函数封装一个方法

export default (dataSource, draggable) => {
    let dragItem = null
    let targItem = null
    const customRow = record => {
        return {
            draggable: draggable,
            ondrag(e) {
                dragItem = record
            },
            ondrop(e) {
                targItem = record
            },
            ondragend(e) {
                if (targItem && dragItem && dragItem !== targItem) {
                    const sourceIndex = dataSource.value.indexOf(dragItem)
                    const targetIndex = dataSource.value.indexOf(targItem)
                    const temp = dataSource.value[sourceIndex]
                    dataSource.value[sourceIndex] = targItem
                    dataSource.value[targetIndex] = temp
                }
            },
            ondragover(e) {
                e.preventDefault()
                return false
            },
        }
    }
    return {
        customRow,
    }
}

钩子命名为useDraggableTable, 它返回一个 customRow 方法

customRow 中参数和方法回调配置:

draggable 配置是否可拖拽

ondrag : 手指按下开始拖动时,需要将拖动的item记录下来

ondrop : 停止拖动时,停留在的item也记录下来

ondragend: 拖动结束,手指松开时,需要判断目标item和开始拖动item是否一致,不一致则交换两者位置

使用钩子

const { customRow } = useDraggableTable(listData, true)

钩子函数传入的是数据源和是否可拖拽,这里的数据需要是有状态的,这样钩子函数中的数据改动才会引起列表的改动