sortable+element 实现表格行拖拽

背景

1、vue项目中的表格需要实现行拖拽功能

2、表格使用element组件库中el-table

方案介绍

Sortable.js

介绍:Sortable.js是一款轻量级的拖放排序列表的js插件

引用自官方文档:No jQuery required. Supports Meteor, AngularJS, React, Polymer, Vue, Knockout and any CSS library, e.g. Bootstrap.

参考地址:https://github.com/SortableJS…

vuedraggable

介绍:基于Sortable.js的vue组件,用以实现拖拽功能

引用自官方文档:Vue drag-and-drop component based on Sortable.js

参考地址:https://github.com/SortableJS…

遇到的问题

在使用vuedraggable的过程中,发现必须用<draggable></draggable>包裹拖动项的父级元素,但是element组件库对table进行封装,无法直接包裹拖动项(即tr)的父级元素
如果你的项目中,表格未使用组件库,实现可以参考https://www.cnblogs.com/xiang…

解决方案

使用 sortable.js

步骤一: 安装

npm install vuedraggable

步骤二:引入

import Sortable from 'sortablejs';

@Component({
  components: {
    Sortable
  }
})

步骤三: el-table 添加row-key属性

<el-table
  ref="filterTable"
  row-key="ip" 
  @filter-change="handlerFilterChange" 
  class="cl-table" 
  :data="resourceList" 
  v-loading="resourceListLoading" 
  stripe style="width:100%;">
  <el-table-column
      prop="name"
    label="主机名" 
    :min-width="150" 
    show-overflow-tooltip>
  </el-table-column>
 </el-table>

步骤四 : 将拖拽元素设置为要拖动项的父级元素

mounted() {
      // 表格中需要实现行拖动,所以选中tr的父级元素
    const table = document.querySelector('.el-table__body-wrapper tbody')
    const self = this
    Sortable.create(table, {
      onEnd({ newIndex, oldIndex }) {
        console.log(newIndex, oldIndex)
        const targetRow = self.resourceList.splice(oldIndex, 1)[0]
        self.resourceList.splice(newIndex, 0, targetRow)
      }
    })
  }
    原文作者:我的名字
    原文地址: https://segmentfault.com/a/1190000019411685
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞