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;
  }
}
相关推荐
二哈喇子!6 分钟前
使用NVM下载Node.js管理多版本
前端·npm·node.js
GGGG寄了32 分钟前
HTML——文本标签
开发语言·前端·html
摘星编程1 小时前
在OpenHarmony上用React Native:ActionSheet确认删除
javascript·react native·react.js
2501_944521591 小时前
Flutter for OpenHarmony 微动漫App实战:推荐动漫实现
android·开发语言·前端·javascript·flutter·ecmascript
Amumu121382 小时前
Vue核心(三)
前端·javascript·vue.js
CoCo的编程之路2 小时前
2026 前端效能革命:如何利用智能助手实现“光速”页面构建?深度横评
前端·人工智能·ai编程·comate·智能编程助手·文心快码baiducomate
RFCEO2 小时前
HTML编程 课程五、:HTML5 新增语义化标签
前端·html·html5·跨平台·语义化标签·可生成安卓/ios·html最新版本
Irene19912 小时前
JavaScript中,为什么需要手动清理事件
javascript·手动清理事件监听器
摘星编程2 小时前
OpenHarmony环境下React Native:Zustand持久化存储
javascript·react native·react.js
2501_944521593 小时前
Flutter for OpenHarmony 微动漫App实战:图片加载实现
android·开发语言·前端·javascript·flutter·php