Drag and drop of element-table rows to change order (no need to download sortableJs

Sample display: vue+element+

By reading the element documentation, we found that element does not provide drag-and-drop related APIs. 

This blog uses the row class name registration function provided by element to realize drag and drop between rows.

1. Set the row style class name of el-table

 Function is used here  

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

 2. Get the row element in mounted

Set row to draggable: true type of drag

Register listening function:

dragstart - Drag start to get the index of the current element being dragged

dragover-Get the new index of the element where the drag is stopped during dragging

dragEnd-drag ends to change the data

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 gets the data of the dragged element

Remove the original elements from the table data and add new elements to the new coordinates

    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 beautification adds blue underline

Note that z-index must be added here, otherwise the underline cannot exceed the table level and cannot be displayed.

.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;
  }
}

おすすめ

転載: blog.csdn.net/weixin_44383533/article/details/132837797