在 Element-UI 的 Table 组件上添加列拖拽效果

在 Element-UI 的 Table 组件上添加列拖拽效果

在这里插入图片描述
一、数据驱动
传统的拖动效果,都是基于通过 mousedown、mousemove、mouseup 事件来修改删减 dom 节点

但 Vue 是一个数据驱动的前端框架,开发时应尽量避免操作 dom

而且 Element-UI 的 Table 组件封装得很严谨,直接操作 dom 很容易产生不可预计的 bug

所以我的核心思路就是:通过一个数组渲染表头(列),然后修改这个数组的顺序,从而修改列表的列排序

template部分

<template>
    <div class="w-table" :class="{ 'w-table_moving': dragState.dragging }">
        <el-table
            :data="data"
            :border="option.border"
            :height="option.height"
            :max-height="option.maxHeight"
            :style="{ width: parseInt(option.width) + 'px' }"
            :cell-class-name="cellClassName"
            :header-cell-class-name="headerCellClassName"
        >
            <slot name="fixed"></slot>
            <el-table-column
                v-for="(col, index) in tableHeader"
                :key="index"
                :prop="col.prop"
                :label="col.label"
                :width="col.width"
                :min-width="col.minWidth"
                :type="col.type"
                :header-align="col.headerAlign"
                :column-key="index.toString()"
                :render-header="renderHeader"
            >
            </el-table-column>
        </el-table>
    </div>
</template>

下面的 data 是列表数据集合,option 是 Table 组件配置项,header 是表头数据集合,由父组件传入

props: {
    data: {
      default: function () {
        return []
      },
      type: Array
    },
    header: {
      default: function () {
        return []
      },
      type: Array
    },
    option: {
      default: function () {
        return {}
      },
      type: Object
    }
  }

配置项可以根据 Element-UI 的 api 自行删减

但有几个参数在组件内部被征用:

1. header-cell-class-name
绑定了一个函数,动态给表头单元格添加 class,从而实现拖动中的虚线效果。

2. cell-class-name

同上。用一个函数给表头以外的所有单元格添加 class,用于区分选中列。

3. column-key

绑定为 header 数组的 index,用于确定需要修改的 header 元素下标

4. render-header

表头渲染函数,用以添加自定义方法,以监听 mousemove 等相关事件

二、记录拖动状态

拖动过程中需要记录几个关键参数:

  data () {
    return {
      tableHeader: this.header,
      dragState: {
        start: -9, // 起始元素的 index
        end: -9, // 移动鼠标时所覆盖的元素 index
        dragging: false, // 是否正在拖动
        direction: undefined // 拖动方向
      }
    }
  }

另外父元素传入了一个表头数据 header,但拖动完成后会修改这个数据

在子组件中直接修改父元素的数据是不推荐的,所以这里初始化了一个 tableHeader 用于托管表头数据 header

但为了让 header 修改时,tableHeader 也能响应修改,就得添加一个监视器 watch

  watch: {
    header (val, oldVal) {
      this.tableHeader = val
    }
  }

三、自定义表头

Element-UI 的 Table 组件为了实现【拖拽边框以修改列宽】的功能,没有将 mousemove、mouseup、mousedown 这三个事件暴露出来

所以需要自定义表头,并手动添加鼠标事件的处理函数,这就需要用到 renderHeader() 方法

 renderHeader (createElement, {column}) {
      return createElement(
        'div', {
          'class': ['thead-cell'],
          on: {
            mousedown: ($event) => { this.handleMouseDown($event, column) },
            mousemove: ($event) => { this.handleMouseMove($event, column) }
          }
        }, [
          // 添加 <a> 用于显示表头 label
          createElement('a', column.label),
          // 添加一个空标签用于显示拖动动画
          createElement('span', {
            'class': ['virtual']
          })
        ])
    },

三个鼠标事件中,第一个参数是事件对象,第二个是表头对象

在对应的处理函数中,可以通过 column.columnKey 获取到对应的表头元素下标 index

空标签 用来显示拖动时的动画(虚线)

四、事件处理

按下鼠标时,记录下起始列。鼠标抬起时,记录下结束列。根据二者之差计算出拖动的方向。

然后根据起始列和结束列的位置,将表头数据重新排序,从而实现列的拖动

拖动过程的处理函数如下:

// 按下鼠标开始拖动
handleMouseDown (e, column) {
  this.dragState.dragging = true
  this.dragState.start = parseInt(column.columnKey)
  // 给拖动时的虚拟容器添加宽高
  let table = document.getElementsByClassName('w-table')[0]
  let virtual = document.getElementsByClassName('virtual')
  for (let item of virtual) {
    item.style.height = table.clientHeight - 1 + 'px'
    item.style.width = item.parentElement.parentElement.clientWidth + 'px'
  }
 document.addEventListener('mouseup', this.handleMouseUp);
},

// 鼠标放开结束拖动
handleMouseUp () {
  this.dragColumn(this.dragState)
  // 初始化拖动状态
  this.dragState = {
    start: -9,
    end: -9,
    dragging: false,
    direction: undefined
  }
 document.removeEventListener('mouseup', this.handleMouseUp);
},

// 拖动中
handleMouseMove (e, column) {
  if (this.dragState.dragging) {
    let index = parseInt(column.columnKey) // 记录起始列
    if (index - this.dragState.start !== 0) {
      this.dragState.direction = index - this.dragState.start < 0 ? 'left' : 'right' // 判断拖动方向
      this.dragState.end = parseInt(column.columnKey)
    } else {
      this.dragState.direction = undefined
    }
  } else {
    return false
  }
},

// 拖动易位
dragColumn ({start, end, direction}) {
  let tempData = []
  let left = direction === 'left'
  let min = left ? end : start - 1
  let max = left ? start + 1 : end
  for (let i = 0; i < this.tableHeader.length; i++) {
    if (i === end) {
      tempData.push(this.tableHeader[start])
    } else if (i > min && i < max) {
      tempData.push(this.tableHeader[ left ? i - 1 : i + 1 ])
    } else {
      tempData.push(this.tableHeader[i])
    }
  }
  this.tableHeader = tempData
},

五、动态样式

在拖动过程中,通过 mousemove 事件,改变当前列的表头状态
然后借助 headerCellClassName, cellClassName 动态修改单元格 class


  headerCellClassName ({column, columnIndex}) {
    let active = columnIndex - 1 === this.dragState.end ? `darg_active_${this.dragState.direction}` : ''
    let start = columnIndex - 1 === this.dragState.start ? `darg_start` : ''
    return `${active} ${start}`
  }

  cellClassName ({column, columnIndex}) {
    return (columnIndex - 1 === this.dragState.start ? `darg_start` : '')
  }

这里的 darg_active 用来给上面的空标签 添加虚线,darg_start 用于实现选中效果

贴一下我自己写的完整样式(使用了 sass 作为编译工具):

<style lang="scss">
.w-table {
 .el-table .darg_start {
   background-color: #f3f3f3; 
  }
  .el-table th {
    padding: 0;
    .virtual{
      position: fixed;
      display: block;
      width: 0;
      height: 0;
      margin-left: -10px;
      background: none;
      border: none;
    }
    &.darg_active_left {
      .virtual {
        border-left: 2px dotted #666;
        z-index: 99;
      }
    }
    &.darg_active_right {
      .virtual {
        border-right: 2px dotted #666;
        z-index: 99;
      }
    }
  }
  .thead-cell {
    padding: 0;
    display: inline-flex;
    flex-direction: column;
    align-items: left;
    cursor: pointer;
    overflow: initial;
    &:before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }
  }
  &.w-table_moving {
    .el-table th .thead-cell{
      cursor: move !important;
    }
    .el-table__fixed {
      cursor: not-allowed;
    }
  }
}

以上代码合起来,展示如下

<template>
    <div class="w-table" :class="{ 'w-table_moving': dragState.dragging }">
        <el-table
            :data="data"
            :border="option.border"
            :height="option.height"
            :max-height="option.maxHeight"
            :style="{ width: parseInt(option.width) + 'px' }"
            :cell-class-name="cellClassName"
            :header-cell-class-name="headerCellClassName"
        >
            <slot name="fixed"></slot>
            <el-table-column
                v-for="(col, index) in tableHeader"
                :key="index"
                :prop="col.prop"
                :label="col.label"
                :width="col.width"
                :min-width="col.minWidth"
                :type="col.type"
                :header-align="col.headerAlign"
                :column-key="index.toString()"
                :render-header="renderHeader"
            >
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
export default {
    data() {
        return {
            tableHeader: this.header,
            dragState: {
                start: -9, // 起始元素的 index
                end: -9, // 移动鼠标时所覆盖的元素 index
                dragging: false, // 是否正在拖动
                direction: undefined // 拖动方向
            }
        };
    },
    props: {
        data: {
            default: function () {
                return [];
            },
            type: Array
        },
        header: {
            default: function () {
                return [];
            },
            type: Array
        },
        option: {
            default: function () {
                return {};
            },
            type: Object
        }
    },
    watch: {
        header(val, oldVal) {
            this.tableHeader = val;
        }
    },
    methods: {
        renderHeader(createElement, { column }) {
            return createElement(
                'div',
                {
                    class: ['thead-cell'],
                    on: {
                        mousedown: ($event) => {
                            this.handleMouseDown($event, column);
                        },
                        mousemove: ($event) => {
                            this.handleMouseMove($event, column);
                        }
                    }
                },
                [
                    // 添加 <a> 用于显示表头 label
                    createElement('a', column.label),
                    // 添加一个空标签用于显示拖动动画
                    createElement('span', {
                        class: ['virtual']
                    })
                ]
            );
        },
        // 按下鼠标开始拖动
        handleMouseDown(e, column) {
            this.dragState.dragging = true;
            this.dragState.start = parseInt(column.columnKey);
            // 给拖动时的虚拟容器添加宽高
            let table = document.getElementsByClassName('w-table')[0];
            let virtual = document.getElementsByClassName('virtual');
            for (let item of virtual) {
                item.style.height = table.clientHeight - 1 + 'px';
                item.style.width = item.parentElement.parentElement.clientWidth + 'px';
            }
            document.addEventListener('mouseup', this.handleMouseUp);
        },

        // 鼠标放开结束拖动
        handleMouseUp() {
            this.dragColumn(this.dragState);
            // 初始化拖动状态
            this.dragState = {
                start: -9,
                end: -9,
                dragging: false,
                direction: undefined
            };
            document.removeEventListener('mouseup', this.handleMouseUp);
        },

        // 拖动中
        handleMouseMove(e, column) {
            if (this.dragState.dragging) {
                let index = parseInt(column.columnKey); // 记录起始列
                if (index - this.dragState.start !== 0) {
                    this.dragState.direction = index - this.dragState.start < 0 ? 'left' : 'right'; // 判断拖动方向
                    this.dragState.end = parseInt(column.columnKey);
                } else {
                    this.dragState.direction = undefined;
                }
            } else {
                return false;
            }
        },

        // 拖动易位
        dragColumn({ start, end, direction }) {
            let tempData = [];
            let left = direction === 'left';
            let min = left ? end : start - 1;
            let max = left ? start + 1 : end;
            for (let i = 0; i < this.tableHeader.length; i++) {
                if (i === end) {
                    tempData.push(this.tableHeader[start]);
                } else if (i > min && i < max) {
                    tempData.push(this.tableHeader[left ? i - 1 : i + 1]);
                } else {
                    tempData.push(this.tableHeader[i]);
                }
            }
            this.tableHeader = tempData;
        },
        headerCellClassName({ column, columnIndex }) {
            let active = columnIndex - 1 === this.dragState.end ? `darg_active_${this.dragState.direction}` : '';
            let start = columnIndex - 1 === this.dragState.start ? `darg_start` : '';
            return `${active} ${start}`;
        },

        cellClassName({ column, columnIndex }) {
            return columnIndex - 1 === this.dragState.start ? `darg_start` : '';
        }
    }
};
</script>
<style lang="scss">
.w-table {
     .el-table .darg_start {
        background-color: #f3f3f3;
    }
    .el-table th {
        padding: 0;
        .virtual {
            position: fixed;
            display: block;
            width: 0;
            height: 0;
            margin-left: -10px;
            background: none;
            border: none;
        }
        &.darg_active_left {
            .virtual {
                border-left: 2px dotted #666;
                z-index: 99;
            }
        }
        &.darg_active_right {
            .virtual {
                border-right: 2px dotted #666;
                z-index: 99;
            }
        }
    }
    .thead-cell {
        padding: 0;
        display: inline-flex;
        flex-direction: column;
        align-items: left;
        cursor: pointer;
        overflow: initial;
        &:before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            bottom: 0;
            right: 0;
        }
    }
    &.w-table_moving {
        .el-table th .thead-cell {
            cursor: move !important;
        }
        .el-table__fixed {
            cursor: not-allowed;
        }
    }
}

六:父组件调用

<template>
<div>
  <wTable :data="tableData" :header="tableHeader" :option="tableOption">
    <el-table-column slot="fixed"
      fixed
      prop="date"
      label="日期"
      width="150">
    </el-table-column>
  </wTable>
</div>
</template>

<script>
import wTable from '@/components/w-table.vue'
export default {
  name: 'Table',
  data () {
    return {
      tableOption: {
        border: true,
        maxHeight: 500
      },
      tableHeader: [{
        prop: 'name',
        label: '姓名',
        sortable: true,
        sortMethod: this.handleNameSort
      }, {
        prop: 'province',
        label: '省份',
        minWidth: '120'
      }, {
        prop: 'city',
        label: '市区',
        minWidth: '120'
      }, {
        prop: 'address',
        label: '地区',
        minWidth: '150'
      }, {
        prop: 'zip',
        label: '邮编',
        minWidth: '120'
      }],

      tableData: [{
        date: '2016-05-03',
        name: '王小虎',
        province: '上海',
        city: '普陀区',
        address: '上海市普陀区金沙江路 1518 弄',
        zip: 200333
      }, {
        date: '2016-05-02',
        name: '王小虎',
        province: '上海',
        city: '普陀区',
        address: '上海市普陀区金沙江路 1518 弄',
        zip: 200333
      }, {
        date: '2016-05-04',
        name: '王小虎',
        province: '上海',
        city: '普陀区',
        address: '上海市普陀区金沙江路 1518 弄',
        zip: 200333
      }, {
        date: '2016-05-01',
        name: '王小虎',
        province: '上海',
        city: '普陀区',
        address: '上海市普陀区金沙江路 1518 弄',
        zip: 200333
      }, {
        date: '2016-05-08',
        name: '王小虎',
        province: '上海',
        city: '普陀区',
        address: '上海市普陀区金沙江路 1518 弄',
        zip: 200333
      }, {
        date: '2016-05-06',
        name: '王小虎',
        province: '上海',
        city: '普陀区',
        address: '上海市普陀区金沙江路 1518 弄',
        zip: 200333
      }]
    }
  },
  methods: {
    handleNameSort () {
      console.log('handleNameSort')
    }
  },
  components: {
    wTable
  }
}
</script>
  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值