sortable.ts 1.41 KB
import Sortable from 'sortablejs'

// 定义一个变量来存储Sortable实例。后续销毁时会用到
let sortableInstance: Sortable | null = null 

/**
 * 拖拽函数
 * @param getList 获取列表数据
 * @param isSort  控制表单是否开启拖拽排序
 */
export const enableRowDrop = (getList: Function) => {
  const tbody = document.querySelector('.el-table.sort-table .el-table__body-wrapper tbody') as any

  if (!tbody) {
    return;
  }

  // 使用更新后的isSort值创建新的Sortable实例
  sortableInstance = new Sortable(tbody, {
    handle: '.sort-icon',
    // ms, number 单位:ms,定义排序动画的时间
    animation: 100,
    scroll: true,
    scrollSensitivity: 30,
    scrollSpeed: 10,
    // 设置拖拽样式类名
    dragClass: 'drop-dragClass',
    // 设置拖拽停靠样式类名
    ghostClass: 'drop-ghostClass',
    // 设置选中样式类名
    chosenClass: 'drop-chosenClass',

    onAdd(evt: any) {
      
    },
    onUpdate(evt: any) {
      
    },
    onRemove(evt: any) {
   
    },
    onStart(evt: any) {
    
    },
    onSort(evt: any) {
     
    },
    
    // 关键代码
    onEnd(evt: any) {
      // 结束拖拽
      console.log('结束表格拖拽', `拖动前索引${evt.oldIndex}---拖动后索引${evt.newIndex}`)
      getList(evt)
    }
  })
}

export const destroySort = () => {
    if (sortableInstance) {
            sortableInstance.destroy()
          }
}