需先安装 vxe-table 以及sortablejs
安装方法: npm install xe-utils vxe-table@legacy
npm install sortablejs --save
重点代码
html 部分:
<div class="draggable" style="padding: 20px">
<vxe-table
border
resizable
ref="xTable1"
:loading="loading"
id="toolbar_demo5"
:custom-config="{storage: true, checkMethod: checkColumnMethod}"
:column-config="{
useKey: true,
minWidth: 200
}"
:seq-config="{startIndex: (pageNum - 1) * pageSize}"
:data="tabledetailsData"
@resizable-change="resizableChangeEvent"
:row-config="{isHover: true}"
:sort-config="{multiple: true, chronological: true}"
@sort-change="sortChangeEvent3">
<vxe-column width="150" v-for="(item,index) in oldList"
:column-key="index.toString()"
:key="`col_${index}`"
:prop="oldList[index].prop"
:field="oldList[index]"
:title="oldList[index]" sortable></vxe-column>
</vxe-table>
</div>
js 部分
引入所需依赖:
data 定义两个变量
核心代码
rowDrop () {
// 此时找到的元素是要拖拽元素的父容器
const tbody = document.querySelector('.draggable .vxe-table--body-wrapper tbody')
const _this = this
Sortable.create(tbody, {
// 指定父元素下可被拖拽的子元素
draggable: '.draggable .vxe-body--row',
onEnd ({newIndex, oldIndex}) {
const currRow = _this.tableData.splice(oldIndex, 1)[0]
_this.tableData.splice(newIndex, 0, currRow)
}
})
},
// 列拖拽
columnDrop () {
this.$nextTick(() => {
const $table = this.$refs.xTable1
this.sortable2 = Sortable.create($table.$el.querySelector('.body--wrapper>.vxe-table--header .vxe-header--row'), {
handle: '.vxe-header--column',
onEnd: ({ item, newIndex, oldIndex }) => {
const { fullColumn, tableColumn } = $table.getTableColumn()
const targetThElem = item
const wrapperElem = targetThElem.parentNode
const newColumn = fullColumn[newIndex]
if (newColumn.fixed) {
const oldThElem = wrapperElem.children[oldIndex]
// 错误的移动
if (newIndex > oldIndex) {
wrapperElem.insertBefore(targetThElem, oldThElem)
} else {
wrapperElem.insertBefore(targetThElem, oldThElem ? oldThElem.nextElementSibling : oldThElem)
}
VXETable.modal.message({ content: '固定列不允许拖动,即将还原操作!', status: 'error' })
return
}
// 获取列索引 columnIndex > fullColumn
const oldColumnIndex = $table.getColumnIndex(tableColumn[oldIndex])
const newColumnIndex = $table.getColumnIndex(tableColumn[newIndex])
// 移动到目标列
const currRow = fullColumn.splice(oldColumnIndex, 1)[0]
fullColumn.splice(newColumnIndex, 0, currRow)
$table.loadColumn(fullColumn)
}
})
})
},