淺談element關於table拖拽排序問題
阿新 • • 發佈:2021-10-06
最近在使用element table的時候,經常會遇到排序的問題,如果只是簡單的排序的話,element官方已經給出了指定的方法
//table的預設排序方式是按ID排序 順序為遞減 這裡可以改成其它 比如 order <el-table :data="tableData" :default-sort="{prop: 'ID',order: 'descending'}"> //設定sortable屬性時出現排序按鈕 <el-table-column prop="ID" label="座號" sortable> </el-table>
但是,element官方元件並不支援拖拽排序,我在這裡引入sortable實現拖拽排序的功能
sortablejs 地址
//安裝sortable.js Install with NPM: $ npm install sortablejs --save //在元件內引入 import Sortable from 'sortablejs' //為需要拖拽排序的表格新增ref屬性 <el-table ref="dragTable"> //在資料渲染完畢新增拖拽事件 created(){ this.getBanner() },methods:{ async getBanner(val){ await apiGetBanner().then((res)=>{ this.bannerTable = res.data.data; }) this.oldList = this.bannerTable.map(v => v.id); this.newList = this.oldList.slice(); this.$nextTick(() => { this.setSort() //資料渲染完畢執行方法 }) } setSort() { const el = this.$refs.dragTable.$el.querySelectorAll( '.el-table__body-wrapper > table > tbody' )[0]; this.sortable = Sortable.create(el,{ // Class name for the drop placeholder,ghostClass: 'sortable-ghost',setData: function(dataTransfer) { dataTransfer.setData('Text','') },//拖拽結束執行,evt執向拖拽的引數 onEnd: evt => { //判斷是否重新排序 if(evt.oldIndex !== evt.newIndex){ let data = { id:this.bannerTable[evt.oldIndex].id,banner_order:evt.newIndex } //資料提交失敗則恢復舊的排序 apiPutBanner(data).catch(()=>{ const targetRow = this.bannerTable.splice(evt.oldIndex,1)[0]; this.bannerTable.splice(evt.newIndex,targetRow); }) } } }) } }
如果需要列拖拽的話,可以參考下面的程式碼,和上面是一樣的原理,在這裡我就不贅述了
//行拖拽 rowDrop() { const tbody = document.querySelector('.el-table__body-wrapper tbody') const _this = this Sortable.create(tbody,{ onEnd({ newIndex,oldIndex }) { const currRow = _this.tableData.splice(oldIndex,1)[0] _this.tableData.splice(newIndex,currRow) } }) },//列拖拽 columnDrop() { const wrapperTr = document.querySelector('.el-table__header-wrapper tr') this.sortable = Sortable.create(wrapperTr,{ anihttp://www.cppcns.commation: 180,delay: 0,onEnd: evt => { const oldItem = this.dropCol[evt.oldIndex] this.dropCol.splice(evt.oldIndex,1) this.dropCol.splice(evt.newIndex,oldItem) } }) }
到此這篇關於淺談element關於table拖拽排序問題的文章就介紹到這了,更多相關element table拖拽排序內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!