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/Sortable

vuedraggable

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

引用自官方文档:Vue drag-and-drop component based on Sortable.js
参考地址:https://github.com/SortableJS/Vue.Draggable

三、解决方案

使用 sortable.js

步骤一 :安装

npm install vuedraggable

步骤二 :引入

import Sortable from 'sortablejs';

步骤三: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)
   }
  })
 }

猜你喜欢

转载自blog.csdn.net/qq_43548590/article/details/130971404