写项目时遇到一个需求就是表头是可以拖动换位置的,并且需要用户手动拖拽设置宽度,我的项目用的是vue+antdesign vue实现的
- 实现列宽的拖拽倒是挺简单的,因为antdesign vue中有说明列宽拖拽怎么实现,
先下载vue-draggable-resizable
然后引入import VueDraggableResizable from 'vue-draggable-resizable';<a-table bordered :rowKey="rowKey" :style="{ '--minHeight': `${pageHeight - 8}px` }" :columns="commonColumns" :row-selection="rowSelection" :loading="loading" :key="key" :data-source="commonData" :pagination="false" :customRow="onClickRowMulti" :rowClassName="getRowClassName" :scroll="{ x: 1000, y: pageHeight - 10 }" :components="components"> </a-table> this.components = { header: { cell: (h, props, children) => { const draggingMap = {}; this.commonColumns.forEach(col => { draggingMap[col.key] = col.width; }); const draggingState = Vue.observable(draggingMap); let thDom = null; const { key, ...restProps } = props; const col = this.commonColumns.find(col => { const k = col.dataIndex || col.key; return k === key; }); if (!col || !col.width) { return h( 'th', { ...restProps }, [children] ); } const onDrag = x => { draggingState[key] = 0; col.width = Math.max(x, 1); }; const onDragstop = () => { if (thDom) { draggingState[key] = thDom.getBoundingClientRect().width; } }; return h( 'th', { ...restProps, attrs: { width: col.width }, 'v-ant-ref': r => (thDom = r), class: 'resize-table-th' }, [ children, h('vue-draggable-resizable', { class: 'table-draggable-handle', on: { dragging: onDrag, dragstop: onDragstop }, key: col.key, props: { w: 10, x: draggingState[key] || col.width, z: 1000, axis: 'x', resizable: false } }) ] ); } } };
就是这么的简单
实现一整列的位置拖拽就得依靠插件来实现了
先下载sortablejs
引入import Sortable from 'sortablejs';/** 列拖拽 */ columnDrop() { const that = this; const wrapperTr = document.querySelector('.ant-table-thead tr'); Sortable.create(wrapperTr, { animation: 180, delay: 0, handle: '.ant-table-header-column', //~~可进行拖拽对应的类名~~~~~~ onUpdate: evt => { var o = evt.oldIndex; var n = evt.newIndex; that.sortListAndUpdate(that.commonColumns, o, n); /**此处是因为在拖拽后,内容排序正常,表头错乱的问题 ---强制进行了重新渲染**/ this.key += 1; this.$nextTick(() => { this.columnDrop(); }); } }); }, // 对表头进行排序,要求 o(oldIndex) 和 n(newIndex) 从 0开始 sortList(list, o, n) { var newColums = JSON.parse(JSON.stringify(list)); var data = newColums.splice(o - 1, 1, null); newColums.splice(o - 1 < n - 1 ? n : n - 1, 0, data[0]); newColums.splice(o - 1 > n - 1 ? o : o - 1, 1); return newColums; }, /** * 对数据排序并更新 table, 要求 o(oldIndex) 和 n(newIndex) 从 0开始 */ sortListAndUpdate(list, o, n) { var newTableData = this.sortList(list, o, n); this.commonColumns = newTableData; } mounted() { this.$nextTick(() => { this.columnDrop(); }); },
这样就可以实现整列的位置拖拽了,你要是想这两个需求同时实现的话,就把他下载一起就可以了,
完事,搞定。。。。。。