背景
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
遇到的問題
在使用vuedraggable的過程中,發現必須用<draggable></draggable>包裹拖動項的父級元素,但是element組件庫對table進行封裝,無法直接包裹拖動項(即tr)的父級元素
如果你的項目中,表格未使用組件庫,實現可以參考 https://www.gxlcms.com/article/162648.htm
解決方案
使用 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) } }) }
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com