el-table表格行拖拽排序或者电子件列表拖拽排序

发布时间 2023-07-20 10:13:11作者: zwbsoft

用到sortablejs  中文官网,http://www.sortablejs.com/

为了页面中可以复用,在common.js下,封装了公用方法

import Sortable from ‘sortablejs’

rowDrop(selector,params,callback){ let tbody = document.querySelector(selector) if(!tbody){ return } if(window.tableSortable){ window.tableSortable.destroy() window.tableSortable =null }
window.tableSortable=Sortable.create(tbody, {     
handle: ".my-handle",
animation: 150,
...params,
onEnd ({ newIndex, oldIndex }) {
callback(newIndex, oldIndex)
}
})
}

//指定只有定义my-handle的div才能执行拖拽操作 

  

页面中使用需要注意几点

1、表格需要定义一个class,便于指定拖拽哪个表格里的行

2、需要定义row-key,唯一的,一般定义为syscode

3、在获取表格数据后,初始化拖拽方法

4、操作列需要加入拖拽图标

 

<el-table class="tableClass" row-key="syscode" :data="tableData" style="width: 100%">
  <el-table-column prop="date" label="日期" width="180"></el-table-column>
  <el-table-column prop="name" label="姓名" width="180"></el-table-column>
  <el-table-column prop="address" label="地址"></el-table-column>
 <el-table-column label="操作">
<template>
        <i class="my-handle iconfont my-icon"></i>
</template>
 </el-table-column>
</el-table>

  

在methods中定义
initDrop(){
   const _this =this
  this.common.rowDrop('.tableClass .el-table__body-wrapper tbody',{},(newIndex, oldIndex)=>{
     let currRow = _this.tableData.splice(oldIndex, 1)[0]
       _this.tableData.splice(newIndex, 0, currRow)
     _this.updateSortSno(_this.tableData) 
      //调取更新排序接口
   })
},
updateSortSno(newlist){
  // 传参,需要把新的数组转成JSON字符串,JSON.stringify(newlist)
  // 调取接口
}

  

如果是div拖拽,需要注意的点

1、外层div,定义class,用来初始化拖拽

2、内层需要拖拽的div,也就是for循环的div,需要定义 key为唯一的值

 

<div class="efileList">
    <div class="item" v-for="(item,index) in fileList" :key="item.syscode">
        {{itemfileName}}
        <i class="my-handle iconfont my-icon"></i>
    </div>
</div>        

  在methods中定义

initDrop(){
   const _this =this
  this.common.rowDrop('.efileList',{
       draggable: ".item"  
    },(newIndex, oldIndex)=>{
     let currRow = _this.tableData.splice(oldIndex, 1)[0]
       _this.tableData.splice(newIndex, 0, currRow)
     _this.updateSortSno(_this.tableData) 
   })
},
//只有定义item的class才能被拖动
 
updateSortSno(newlist){
   //传参,需要把新的数组转成JSON字符串,JSON.stringify(newlist)
   //调取接口
}