首先:安装sortablejs库。
网上搜的例子都不能正确排序,但是序号会变化。经过尝试发现了最终的解决办法。
<template>
<div>
<el-table
:data="tableData"
border
row-key="id"
align="left"
>
<el-table-column
v-for="(item, index) in col"
:key="`col_${index}`"
:prop="col[index].prop"
:label="item.label"
>
</el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
data() {
return {
col: [
{
label: '顺序',
prop: 'order'
},
{
label: '日期',
prop: 'date'
},
{
label: '姓名',
prop: 'name'
},
{
label: '地址',
prop: 'address'
}
],
tableData: [
{
order: 0,
date: '2016-05-02',
name: '王小虎',
address: '上海市普陀区金沙江路 1518 弄'
},
{
order: 1,
date: '2016-05-04',
name: '王小虎',
address: '上海市普陀区金沙江路 1517 弄'
},
{
order: 2,
date: '2016-05-01',
name: '王小虎',
address: '上海市普陀区金沙江路 1519 弄'
},
{
order: 3,
date: '2016-05-03',
name: '王小虎',
address: '上海市普陀区金沙江路 1516 弄'
}
]
}
},
mounted() {
// 阻止默认行为
document.body.ondrop = function(event) {
event.preventDefault()
event.stopPropagation()
}
this.rowDrop()
},
methods: {
// 行拖拽
rowDrop() {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
const _this = this
Sortable.create(tbody, {
onEnd({ newIndex, oldIndex }) {
const tempData = _this.tableData
_this.tableData = []
const currRow = tempData.splice(oldIndex, 1)[0]
tempData.splice(newIndex, 0, currRow)
_this.$nextTick(() => {
_this.tableData = tempData
})
}
})
}
}
}
</script>
以上代码最关键的是要把原数据置空。
_this.tableData = []
走过的坑:有试过重新渲染的方式,但是重新渲染后,只能拖拽一次。因为重新渲染后,附加的拖拽事件没了。