vue3 + Element plus + Ts + Sortable.js 实现table拖拽排序

1、安装Sortable.js插件

使用npm install sortable.js --save 或者 yarn add sortable.js

2、还需还要注意是否安装了types/sortablejs插件,如果没有安装还需安装

使用yarn add @types/sortablej 安装或者npm安装视情况而定(不要一会儿npm,一会儿yarn可能会报错,因为两个方法安装的文件路径不同)

3、引入sortable.js

import Sortable from 'sortablejs'

具体详细参数可以看官网:sortable.js中文文档 - itxst.com

4、代码如下 

 <el-table
            @sort-change="handleTableSort"
            :data="tableData"
            :header-cell-style="{ background: '#F2F3F8', color: '#1D2129' }"
            style="width: 100%"
            ref="dragTable"
          >
            <el-table-column width="180">
              <template #default>
                <el-icon class="move-icon cursor-pointer"><Switch /></el-icon>
              </template>
            </el-table-column>
            <el-table-column label="优先级" property="agreement"> </el-table-column>
            <el-table-column label="URL" property="port"> </el-table-column>
            <el-table-column label="说明 " property="jumpPort" showOverflowTooltip>
            </el-table-column>

            <el-table-column label="操作" align="right" width="200">
              <template #default="scope">
                <el-switch
                  class="mr-4"
                  :active-value="1"
                  :inactive-value="2"
                  v-model="scope.row.jumpType"
                />
                <el-button link type="primary" @click="DelRow(scope.$index, scope.row)">
                  设置</el-button
                >
                <el-button link type="danger" @click="DelRow(scope.$index, scope.row)">
                  删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
import {  ref, onMounted, nextTick } from 'vue'

import Sortable from 'sortablejs'

const dragTable = ref()

const initDropTable = () => {
  const el = dragTable.value.$el.querySelector('.el-table__body tbody')
  Sortable.create(el, {
    handle: '.move-icon', //设置指定列作为拖拽
    onEnd(evt: any) {
      const { newIndex, oldIndex } = evt
      console.log(newIndex)
      console.log(oldIndex)
      const currRow = tableData?.splice(oldIndex, 1)[0]
      tableData?.splice(newIndex, 0, currRow)
      sortIndex()
    }
  })
}

const sortIndex = () => {
  const array = []
  tableData.forEach((e, i) => {
    const obj = {
      currency_id: e.currency_id,
      index: i + 1
    }
    array.push(obj)
  })
}


onMounted(() => {
  nextTick(() => {
    initDropTable()
  })
})

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值