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;
  }
}
相关推荐
人工智能训练师4 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny074 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy5 小时前
css的基本知识
前端·css
昔人'5 小时前
css `lh`单位
前端·css
前端君5 小时前
实现最大异步并发执行队列
javascript
Nan_Shu_6146 小时前
Web前端面试题(2)
前端
知识分享小能手7 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队7 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光8 小时前
css之一个元素可以同时应用多个动画效果
前端·css
萌萌哒草头将军8 小时前
Oxc 和 Rolldown Q4 更新计划速览!🚀🚀🚀
javascript·vue.js·vite