Ant Design Vue 表格实现可拖动的伸缩列

步骤一:安装集成的 vue-draggable-resizable 插件,npm下载报错,有安装了cnpm也可以
npm install --save vue-draggable-resizable
步骤二:在src文件夹内创建mixins文件夹,在mixins文件夹内创建tableDragResize.js
import Vue from "vue";
import VueDraggableResizable from "vue-draggable-resizable";

Vue.component("vue-draggable-resizable", VueDraggableResizable);
function initDrag(columns) {
  const draggingMap = {};
  columns.forEach((col) => {
    draggingMap[col.key] = col.width;
  });
  const draggingState = Vue.observable(draggingMap);
  return (h, props, children) => {
    let thDom = null;

    const { key, ...restProps } = props;
    let col;
    if (key === "selection-column") {
      //表格加了复选框,不加这个判断col会是undefided
      col = {};
    } else {
      col = columns.find((col) => {
        const k = col.dataIndex || col.key;
        return k === key;
      });
    }
    if (!col || !col.width) {
      return {children};
    }
    const onDrag = (x) => {
      draggingState[key] = 0;
      col.width = Math.max(x, 1);
    };

    const onDragstop = () => {
      draggingState[key] = thDom.getBoundingClientRect().width;
    };
    return (
       (thDom = r)}
        width={col.width}
        class="resize-table-th"
      >
        {children}
        
      
    );
  };
}
export default {
  methods: {
    drag(columns) {
      return {
        header: {
          cell: initDrag(columns),
        },
      };
    },
  },
};
步骤三:在使用页面中引入tableDragResize.js, 同时添加 mixins: [tableDragResize]

步骤四:table 组件中添加components属性,drag(columns)方法的参数是当前表头集合数据


步骤五:添加以下样式
/deep/.table-draggable-handle {
  border:1px solid red;
  height: 100% !important;
  left: auto !important;
  right: -5px;
  cursor: col-resize;
  touch-action: none;
  border: none;
  position: absolute;
  transform: none !important;
  bottom: 0;
}
/deep/.resize-table-th {
  position: relative;
}

注意点:

1,表头columns中,每列都要设置width,width的值必须Number,如果不设置width属性,拖动时不生效;
2,style一定要记得添加.table-draggable-handle 和 .resize-table-th 两个class。并且style标签不能添加scoped属性。

你可能感兴趣的:(Ant Design Vue 表格实现可拖动的伸缩列)