Vue3+element plus+sortablejs实现table列表拖拽

1、安装

npm install sortablejs --save

2、引入

import Sortable from 'sortablejs';

3、使用

  • 表格表头必须加row-key,否则会出现排序错乱
  • 完整代码table.vue
<el-table v-loading="loading"
              row-key="id"
              :height="tableHeight"
              ref="tableRef"
              border
              stripe
              size="small"
              :data="receiptDataList"
              :row-class-name="setRowColor"
              show-summary
              :summary-method="getSummaries"
              @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="45" align="center"/>
      <el-table-column
          v-for="(item, index) in tableHeaderList"
          :key="`col_${index}_${mykey}`"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :sortable="item.sortable"
          :show-overflow-tooltip="item.overflow"
          align="center"
      >
        <template #default="{row}" v-if="item.label === '收款编码'">
          <span>{{ row.no }}</span>
        </template>
        <template #default="{row}" v-if="item.label === '箱号'">
          <span>{{ row.caseNum }}</span>
        </template>
         .......
      </el-table-column>
</el-table>
onMounted(() => {
   columnDrop()
   rowDrop()
})
//列拖拽:列拖拽方法实际上就是修改表头数据的值
const mykey = ref(0)
function columnDrop() {
  const wrapperTr  = document.querySelector('.el-table__header-wrapper tr');
  Sortable.create(wrapperTr , {
    animation: 180,
    delay: 0,
    onEnd: evt => {
      // 跳过显示的列数量,如开头我们用了一个多选框
      const empty = 1
      const oldItem = tableHeaderList.value[evt.oldIndex- empty];
      tableHeaderList.value.splice(evt.oldIndex- empty, 1);
      tableHeaderList.value.splice(evt.newIndex- empty, 0, oldItem);
      //防止表头数据改变,但表头未重新渲染
      //在自定义表头的时候,由于是用的v-for循环生成的,因此会给每个循环体一个固定的key,导致数据频繁异步更新时,因为这个key没有变,所以el-table觉得表头数据是没有变化的,因此就只更新了整体表格数据、key值有变化的列的表头。
      mykey.value = Math.floor(Math.random()*1000+1) 
    }
  });
}

//行拖拽:行拖拽方法实际上就是修改this.tableData的值
function rowDrop() {
  // 要侦听拖拽响应的DOM对象
  const tbody = document.querySelector('.el-table__body-wrapper tbody');
  Sortable.create(tbody, {
    // 结束拖拽后的回调函数
    onEnd({newIndex, oldIndex}) {
      console.log('拖动了行,当前序号:' + newIndex);
      const currentRow = receiptDataList.value.splice(oldIndex, 1)[0];
      receiptDataList.value.splice(newIndex, 0, currentRow);
    }
  })
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值