最近在使用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官方組件並不支持拖拽排序,我在這裏引入sortablejs實現拖拽排序的功能
- sortablejs GitHub地址
//sortablejs GitHub地址
https://github.com/SortableJS/Sortable#readme
//安裝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, 0, 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, 0, currRow)
}
})
},
//列拖拽
columnDrop() {
const wrapperTr = document.querySelector('.el-table__header-wrapper tr')
this.sortable = Sortable.create(wrapperTr, {
animation: 180,
delay: 0,
onEnd: evt => {
const oldItem = this.dropCol[evt.oldIndex]
this.dropCol.splice(evt.oldIndex, 1)
this.dropCol.splice(evt.newIndex, 0, oldItem)
}
})
}