sortablejs + vue +element-table 完成拖拽表格
问题:sortablejs 拖拽以后表格列的宽度没有根据拖拽完成宽度的变化 试了很多方法没有解决
目的:在很多社区上找了下sortablejs 这个问题 但是都是无果的 只有自己来进行尝试 居然成功了 所以也分享给大家
多的不说上代码 上截图
-
代码实现
<template> <div class="main-content"> <el-table :data="tableData" border stripe row-key="id" align="left"> <el-table-column v-for="(item, index) in col" :key="`col_${index}`" :prop="dropCol[index].prop" :label="item.label" :width="item.width" ></el-table-column> </el-table> <div class="datashow-box"> <div class="columndata"> <h4>列拖拽时的数据变化:</h4> <pre style="text-align: left">{{dropCol}}</pre> <pre style="text-align: left">{{col}}</pre> </div> <div class="rowdata"> <h4>行拖拽时的数据变化:</h4> <pre style="text-align: left">{{tableData}}</pre> </div> </div> </div> </template> <script> import Sortable from 'sortablejs' export default { data () { return { col: [ { label: '日期', prop: 'date', width: 100 }, { label: '姓名', prop: 'name' }, { label: '地址', prop: 'address' } ], dropCol: [ { label: '日期', prop: 'date', width: 100 }, { label: '姓名', prop: 'name' }, { label: '地址', prop: 'address' } ], tableData: [ { id: '1', date: '2016-05-01', name: '王小虎1', address: '上海市普陀区金沙江路 101 弄' }, { id: '2', date: '2016-05-02', name: '王小虎2', address: '上海市普陀区金沙江路 102 弄' }, { id: '3', date: '2016-05-03', name: '王小虎3', address: '上海市普陀区金沙江路 103 弄' }, { id: '4', date: '2016-05-04', name: '王小虎4', address: '上海市普陀区金沙江路 104 弄' } ] } }, mounted () { this.rowDrop() this.columnDrop() }, methods: { // 行拖拽 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: 120, delay: 0, onEnd: evt => { const oldItem = this.dropCol[evt.oldIndex] this.dropCol.splice(evt.oldIndex, 1) this.dropCol.splice(evt.newIndex, 0, oldItem) } }) } } } </script> -
拖拽之前的
-
拖拽之后的
不难发现 拖拽后第一列的地址列变窄了 各种调试以后发现 还是无果 最后一句代码就解决了这个问题
将width 改为dropCol[index].width
<el-table :data="tableData" border stripe row-key="id" align="left">
<el-table-column
v-for="(item, index) in col"
:key="`col_${index}`"
:prop="dropCol[index].prop"
:label="item.label"
:width="dropCol[index].width"
></el-table-column>
</el-table>
再来看看
问题完美解决