样例展示: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;
}
}