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;
  }
}
相关推荐
_丿丨丨_5 小时前
XSS(跨站脚本攻击)
前端·网络·xss
天天进步20155 小时前
前端安全指南:防御XSS与CSRF攻击
前端·安全·xss
呼啦啦呼啦啦啦啦啦啦6 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
拾光拾趣录7 小时前
括号生成算法
前端·算法
拾光拾趣录8 小时前
requestIdleCallback:让你的网页如丝般顺滑
前端·性能优化
前端 贾公子8 小时前
vue-cli 模式下安装 uni-ui
前端·javascript·windows
拾光拾趣录8 小时前
链表合并:双指针与递归
前端·javascript·算法
@大迁世界8 小时前
前端:优秀架构的坟墓
前端·架构
拼图2098 小时前
element-plus——图标推荐
javascript·vue.js·elementui
期待のcode8 小时前
图片上传实现
java·前端·javascript·数据库·servlet·交互