• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Vue element表格实现拖动排序

武飞扬头像
码农小宋
帮助1

最近在vue项目开发时,领导提了一个需求,需要实现自由拖动element表格进行排序,小编上网查了很多方法,最终实现了这个功能。在这里小编跟大家分享一下如何实现这个功能的。

首先我们需要安装sortable.js这款插件

npm install sortablejs

然后我们在js中引入这个插件

import Sortable from "sortablejs";

表格加上row-key=“id”   我这里id是 stepsId

  <el-table :data="tableData" ref="singleTable" highlight-current-row border row-key="stepsId" class="load_table">
      <el-table-column prop="stepsId"  width="50" label="编号" align="center"></el-table-column>
      <el-table-column prop="name"  width="50" label="姓名" align="center" prop="index"></el-table-column>
   </el-table>

实现排序方法如下所示:  

 mounted(){//页面挂在完成触发
    this.dragSort();
  },
   //表格拖动排序
    dragSort() {
            const el = this.$refs.singleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
            this.sortable = Sortable.create(el, {
              ghostClass: 'sortable-ghost',
              setData: function (dataTransfer) {
                dataTransfer.setData('Text', '')
              },
              onEnd: e => {
              //e.oldIndex为拖动一行原来的位置,e.newIndex为拖动后新的位置
                const targetRow = this.stepsList.splice(e.oldIndex, 1)[0];
                this.stepsList.splice(e.newIndex, 0, targetRow);
                var stepsIdArr = [];//重组合后的id循序
                this.stepsList.forEach(x=>{
                  stepsIdArr.push(x.stepsId);
                })
                //更改排序号接口
                updateSortNo({stepsIds:stepsIdArr}).then(res=>{
                  console.log("res.data",res.data);
                })
              }
            })

          },

this.singleTable: 对应表格的ref对象

this.sortable: 需要在data里定义

this.stepsList: table的表格list对象

 到这一步,我们已经实现页面自由拖动表格的功能了 ,我的处理逻辑是排序后拿到新数组的id去接口按照新数组循序根据下标直接更改排序号。所以只传了排序好后的id就可以了

学新通

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhibehkh
系列文章
更多 icon
同类精品
更多 icon
继续加载