element-table 行的拖拽更改顺序(无需下载sortableJs

样例展示:vue+element+

通过阅读element文档我们发现element并不提供拖拽相关的api

本博客通过element提供的行类名 注册函数 实现行与行的拖拽

1.设置el-table 的行样式类名

这里是用的是 function

html 复制代码
            <el-table
              :data="outputData"
              :row-class-name="activeClass"
              class="outputTable"
              >
               .....
             </el-table>
javascript 复制代码
    activeClass ({ row, rowIndex }) {
      if (rowIndex === this.newDragIndex) {
        return 'isDragBox active-drag'
      }
      return 'isDragBox'
    }

2.在mounted获取到row元素

将row设置为的draggable:true拖拽的类型

注册监听函数:

dragstart-拖拽开始 获取拖拽的当前元素index

dragover-拖拽中途 获取拖拽停留的元素的new index

dragEnd-拖拽结束 将数据进行变化

javascript 复制代码
this.$nextTick(() => {
    const dragBox = document.querySelectorAll('.outputTable .isDragBox')
    dragBox.forEach((i, idx) => {
        i.setAttribute('draggable', 'true')
        i.ondragstart = () => this.dragStartItem(idx)
        i.ondragover = () => this.dragOverItem(idx)
        i.ondragend = () => this.dragEndItem()
    })
})

3.dragEnd获取拖拽元素的数据data

将table表格数据去除掉原有的元素 ,将新元素添加到新坐标

javascript 复制代码
    dragStartItem (idx) {
      this.dragIndex = idx
    },
    dragOverItem (index) {
      this.newDragIndex = index
    },
    dragEndItem () {
      const data = this.outputData[this.dragIndex]
      this.outputData.splice(this.dragIndex, 1)
      this.outputData.splice(this.newDragIndex, 0, data)
    },

4.css美化 增加蓝色下划线

注意这里 z-index一定要加否则下划线无法超过table层级无法显示

css 复制代码
.isDragBox{
    cursor: move;
    position: relative;
}
.active-drag{
     position: relative;
      &::after {
        content: '';
        position: absolute;
        top: -1px;
        left: 0;
        width: 100%;
        height: 2px;
        background-color: #4B79F3;
        z-index:99;
  }
}
相关推荐
老毛肚1 小时前
软件测试期末考试
vue.js
海兰1 小时前
【web应用】Excel 项目数据自动化分析系统(AI 驱动分析)详细设计与部署指南(附源代码)
前端·人工智能·自动化·excel
小二·1 小时前
Next.js 15 全栈开发实战
开发语言·javascript·ecmascript
2501_940041741 小时前
技术分享:高质量全栈开发提示词设计实践 —— 覆盖简单到复杂
前端·prompt
IT_陈寒2 小时前
Python的os.path.join居然能这么坑?
前端·人工智能·后端
艳阳天_.2 小时前
星瀚弹框页面实现
java·前端·python
杨若瑜2 小时前
本地开发环境慢?localhost的锅!
vue.js
EdgeOne边缘安全加速平台2 小时前
EdgeOne Web 防护×AI 升级:让 AI 既参与攻击识别,也参与误报纠错
前端·人工智能·腾讯云·edgeone
nuIl2 小时前
实现一个 Coding Agent(6):并行工具调用
前端·ai编程·cursor
Rain5092 小时前
2.1 Nest.js 项目初始化与模块化架构
开发语言·前端·javascript·后端·架构·数据分析·node.js