1、先看需求:
原来的:
想要的:
ps:图片不直观,目的就是可以让列去拖拽,让某些列按照你拖拽的排序去展示。视频上传不了,包涵!
1、首先组件库不支持列拖拽,ok,自己来,使用其它js库来实现。
npm install sortablejs --save
有兴趣的可以去sortablejs 官网看下。
2、导入插件:
import Sortable from 'sortablejs'
3、上代码:
html:el-table组件,我这里用的是封装的,没有封装的话,就直接使用<el-table></el-table>
<!-- 表格数据,只展示和列拖拽相关的代码 -->
<EleUITable
:rowKey="columnDropId"
>
js:
// 计算属性 给到上面的rowKey,且rowKwy必须绑定唯一值
computed: {
columnDropId() {
this.customHeader.headData.forEach(e => {
if (e.name) {
return e.name
} else {
return e.type
}
})
}
},
// 生命周期
mounted(){
this.dropCol = this.customHeader.headData
this.getCustomHeader()
this.columnDrop()
},
// 方法
methods: {
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)
// 下面是我自己的业务逻辑,同仁们可自行对自己的业务逻辑进行分析
// this.customHeader.headData = this.dropCol
// this.isColumnDrop = this.dropCol
}
})
},
4、上面的代码copy完,有遇到bug吗?我这边遇到bug了,bug:列拖拽后,表头不动,数据动了,就像:原来的表头是[1,2,3],将表头1和2互调位置,但拖拽后的表头还是[1,2,3],表头1和2的数据却改变了。原因就是el-table封装时使用了v-for,绑定的key值不是唯一的,才导致这个问题。将key值变成唯一性即可。
多说一句:
之前在用el-table组件的时候,一个页面用了多个el-table,绑定的key值也都是i,导致表格数据混乱,所以这个key值最好还是保证唯一性吧。
ok,有什么问题请及时提出来,避免误导他人,感谢!