element table 表格拖动 sortable.js

开发遇到一个需求

客户不满意当前列表排序,想实现实施拖动改变顺序

 用sortable.js 可以完美解决该问题

 <el-table
            :data="listData"
            stripe
            border
            ref="tableList"
        >
          <el-table-column label="序号" prop="index" align="center" width="50"/>
          <el-table-column prop="itemName" label="测试名称" align="center" show-overflow-tooltip/>
          <el-table-column prop="itemCode" label="方法标准编号" align="center" show-overflow-tooltip/>
          <el-table-column prop="detectResult" label="检验结果" align="center" show-overflow-tooltip/>
          <el-table-column prop="subcontract" label="是否委外" align="center">
            <template slot-scope="{row, $index}">
              {{row.subcontract ? '是': '否'}}
            </template>
          </el-table-column>
        </el-table>
    import Sortable from 'sortablejs'

this.$nextTick(() => {
                const el = this.$refs.tableList.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0]
                new Sortable(el, {
                 animation: 150,
                  draggable: "tr",
                  handle: "tr",
                  dataIdAttr: 'detectItemFlag',
                  onStart: ({oldIndex}) => {
                   console.log('起始位置',oldIndex)
                   this.startIndex = oldIndex
                  },
                  onChange:(evt) => {
                    // 改变序列
                    // oldIndex > newIndex 表示移动了两个列
                    const { newIndex } = evt;
                    // 拖动时实时更新索引,每拖动一列都会更新索引
                    // 先交换数据
                    this.endIndex = newIndex
                    if ( this.startIndex !==  this.endIndex) {
                      // 交换listData中两个数据的位置
                      [this.listData[this.startIndex], this.listData[this.endIndex]] = [this.listData[this.endIndex], this.listData[ this.startIndex]];
                    }
                    // 交换完数据 oldIndex 应该为 newIndex
                    this.startIndex = newIndex
                  },
                  onEnd: (evt) => {
// 结束拖动后更新索引值
                    this.listData.map((item, index) => {
                      item.index = index + 1;
                    });

                  }
                })
              })

最终效果: 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值