表格拖拽应该是个很基础的功能了,一般功能全一些的table插件都会带着,并且文档也简洁易懂,然而,我却在ant-design-vue这个ui组件库碰了壁,官方表格伸缩列示例粘贴过来会报错的好嘛,再加上这个功能甲方爸爸提了很多次,就不得不勇敢面对了!!那就让我用baidu、google + c v 大法来解决下,结果网上的文章不是不能用就是不好用,那就只能靠自己了,下面就把代码贴上,在贴上前,要先安装两个jsx的插件和vue-draggable-resizable拖拽插件,很简单,命令如下
npm install --save-dev @vue/babel-preset-jsx @vue/babel-helper-vue-jsx-merge-props
//或者
yarn add @vue/babel-preset-jsx @vue/babel-helper-vue-jsx-merge-props -D
//然后 安装vue-draggable-resizable插件 注意版本号是2.1.0
npm install vue-draggable-resizable@2.1.0
//或者
yarn add vue-draggable-resizable@2.1.0
然后新建个vue文件,把下面代码粘上去
<script>
import Vue from "vue";
import VueDraggableResizable from "vue-draggable-resizable";Vue.component("vue-draggable-resizable", VueDraggableResizable);const columns = [{title: "Date",dataIndex: "date",width: 200,},{title: "Amount",dataIndex: "amount",width: 100,},{title: "Type",dataIndex: "type",width: 100,},{title: "Note",dataIndex: "note",width: 100,},{title: "Action",key: "action",scopedSlots: { customRender: "action" },},
];const draggingMap = {};
columns.forEach((col) => {draggingMap[col.key] = col.width;
});// const draggingState = Vue.observable(draggingMap); 状态共享,如果你需要的话可以加上 vue 需要2.6.0以上
export default {name: "sortTable",data() {return {datas: [{key: 0,date: "2018-02-11",amount: 120,type: "income",note: "transfer",},{key: 1,date: "2018-03-11",amount: 243,type: "income",note: "transfer",},{key: 2,date: "2018-04-11",amount: 98,type: "income",note: "transfer",},],draggingState: draggingMap,};},render(h) {return (<a-tableborderedcolumns={columns}components={
{header: {cell: (h, props, children) => {let thDom = null;const { key, ...restProps } = props;const col = columns.find((col) => {const k = col.dataIndex || col.key;return k === key;});if (!col.width) {return <th {...restProps}>{children}</th>;}const onDrag = (x) => {this.draggingState[key] = 0;col.width = Math.max(x, 1);};const onDragstop = () => {this.draggingState[key] = thDom.getBoundingClientRect().width;};return (<th{...restProps}v-ant-ref={(r) => (thDom = r)}width={col.width}class="resize-table-th">{children}<vue-draggable-resizablekey={col.key}class="table-draggable-handle"w={10}x={this.draggingState[key] || col.width}z={1}axis="x"draggable={true}resizable={false}onDragging={onDrag}onDragstop={onDragstop}></vue-draggable-resizable></th>);},},}}data-source={this.datas}></a-table>);},
};
</script>
<style lang="less">
.resize-table-th {position: relative;.table-draggable-handle {height: 100% !important;bottom: 0;left: auto !important;right: -5px;cursor: col-resize;touch-action: none;}
}
</style>
好了,现在你在看看是不是可以拖拽了?不行?留言我来帮你解决