vue3关于vxe-table可拖拽排序的自定义指令

代码中使用到的插件有sortablejs和lodash

指令参数:
  • arg:排序字段
  • value:vxe-table表格的实例对象
import Sortable from "sortablejs";
import { cloneDeep } from 'lodash'

/**
 *
 * @param oldIndex
 * @param newIndex
 * @param tableData 表数据
 * @param field 排序字段
 * @returns {*[]}
 */
const getOrderList = ({oldIndex,newIndex,tableData,field}) => {
    const newList = cloneDeep(tableData)
        // 第一种:向上移动
    if (oldIndex > newIndex) {
        for(let index = newList.length; index > 0; index--) {
            if (index < oldIndex && index >= newIndex) {
                const curr = newList[index]
                const prev = newList[index + 1]
                newList[index] = cloneDeep(prev)
                newList[index + 1] = cloneDeep(curr)
                newList[index][field] = curr[field]
                newList[index + 1][field] = prev[field]
            }
        }
        // 第二种:向下移动
    } else if (oldIndex < newIndex) {
        for(let index = 0; index < newList.length; index++) {
            if (index > oldIndex && index <= newIndex) {
                const curr = newList[index]
                const next = newList[index - 1]
                newList[index] = cloneDeep(next)
                newList[index - 1] = cloneDeep(curr)
                newList[index][field] = curr[field]
                newList[index - 1][field] = next[field]
            }
        }

    } // 第三种:没有移动,不操作
    return newList
}

export const vSortable = (el,binding) => {
    const {arg: field,value: xGrid} = binding

    const tbody = el.querySelector(".vxe-table--body tbody")
    if(!xGrid) return
    setTimeout(() => {
        let tableData = []
        const column = xGrid.getColumnByField(field)
        new Sortable(tbody,{
            animation: 200,
            handle: `[colid=${column.id}]`,
            ghostClass: "sortable-ghost",
            direction: "vertical",
            onEnd: ({oldIndex,newIndex}) => {
                const newList = getOrderList({oldIndex,newIndex,tableData,field})

                xGrid.reloadData(newList)
            },
            onStart: () => {
                tableData = xGrid.getTableData().tableData
            },
        })
    })
}

示例

<vxe-grid v-sortable:sort="xGrid" ref="xGrid" v-bind="gridOptions" :data="data">
</vxe-grid>
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值