element table拖拽排序sortable.js

文章介绍了如何通过npm安装SortableJS库,并在Vue项目的el-table组件中实现行拖拽排序功能。通过设置handle、draggable等配置项,以及onMove和onEnd事件处理拖动过程和完成后的逻辑,确保数据同步更新。同时解决了拖动后单元格宽度失效的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

npm install sortablejs --save

官网
http://www.sortablejs.com/index.html
配置项
http://www.sortablejs.com/options.html

<el-table 
        :data="tableData"
        border
        row-key="id"
        :cell-style="tableCellStyle"
        ></el-table>
//行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        forceFallback: true,
        handle:".move",
        draggable:'.el-table__row', // 允许拖拽的项目类名
        onMove:(customEvent)=> {
	          // 禁止在拖拽过程中交换位置
	          // 可将初始位置及目标位置进行记录
	          _this.oldIndex = customEvent.dragged.rowIndex; //  初始位置
	          _this.newIndex = customEvent.related.rowIndex; // 目标位置
            console.log(_this.oldIndex,_this.newIndex)
	          // return false;  // 不进行交换
	          // 返回值有三个
	          // return false; — for cancel
	          // return -1; — insert before target
	          // return 1; — insert after target
	        },
        onEnd:({newIndex, oldIndex})=> {
          console.log('拖拽完成,初始位置及目标位置重置',newIndex, oldIndex)
          // 拖拽完成,初始位置及目标位置重置
          _this.newIndex = null;
          _this.oldIndex = null;
          // const { newIndex, oldIndex } = _this;
          if(newIndex === oldIndex){
            return
          }
          
          const currRow = _this.tableData.splice(oldIndex, 1)[0];
          _this.tableData.splice(newIndex, 0, currRow);
          
          _this.tableData.forEach((item,index)=>{
            item.sortCode = index
          })
          
          this.changeSave()
        }
      })
    },
//解决拖动项宽度失效
tableCellStyle({row, column, rowIndex, columnIndex}){
      return{
        'width':column.realWidth+'px'
      }
    },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值