sortable+element 實現表格行拖拽

背景

一、vue項目中的表格須要實現行拖拽功能html

二、表格使用element組件庫中el-tablevue

方案介紹

Sortable.js

介紹:Sortable.js是一款輕量級的拖放排序列表的js插件git

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

參考地址:https://github.com/SortableJS...github

vuedraggable

介紹:基於Sortable.js的vue組件,用以實現拖拽功能npm

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

參考地址:https://github.com/SortableJS...app

遇到的問題

在使用vuedraggable的過程當中,發現必須用<draggable></draggable>包裹拖動項的父級元素,可是element組件庫對table進行封裝,沒法直接包裹拖動項(即tr)的父級元素
若是你的項目中,表格未使用組件庫,實現能夠參考https://www.cnblogs.com/xiang...ui

解決方案

使用 sortable.js this

步驟一: 安裝插件

npm install vuedraggable

步驟二:引入code

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)
      }
    })
  }
相關文章
相關標籤/搜索