效果如图,姓名 数值1 字段进行自动合并
封装合并列js - tableMerge.js
// 获取列合并的行数
// params
// tableData: 表格数据
// mergeId: 合并的列的字段名
export const tagRowSpan = (tableData, mergeId) =>{const tagArr = [];let pos = 0;tableData.map((item, index) => {if (index === 0) {tagArr.push(1);pos = 0;} else if (tableData[index][mergeId] === tableData[index - 1][mergeId]) {// 合并项目tagArr[pos] += 1;tagArr.push(0);} else {tagArr.push(1);pos = index;}});return tagArr;
}
// 列方法
export const handleSpanMethod = ({ rowIndex, columnIndex, column }, tagArr, needMergeCol) => {if (needMergeCol.includes(columnIndex)) {const _row = tagArr[column.property][rowIndex];const _col = _row > 0 ? 1 : 0;return {rowspan: _row,colspan: _col,};}
}
拖拽使用sortablejs
npm install sortablejs -S
使用实例
如果拖拽列 要动态生成列
<template><el-table :data="tableData.data" border style="width: 100%; margin-top: 20px":span-method="(param) => handleSpanMethod(param, tableData.spanMap, needMergeCol)" ref="dragTable" ><el-table-column :prop="col.prop" :label="col.label" v-for="(col, index) in colData" :key="col.prop + index"></el-table-column></el-table>
</template><script>
import Sortable from 'sortablejs'
import { tagRowSpan ,handleSpanMethod} from '@/utils/tableMerge.js'
export default {data () {return {colData: [{prop: 'name',label: '姓名'},{prop: 'id',label: 'ID',width: '180'},{prop: 'amount1',label: '数值 1(元)'},{prop: 'amount2',label: '数值 2(元)'},{prop: 'amount3',label: '数值 3(元)'}],tableData: {data: [{id: '1',name: '王小虎1',amount1: '234',amount2: '3.2',amount3: 10}, {id: '2',name: '王小虎1',amount1: '234',amount2: '4.43',amount3: 12}, {id: '3',name: '王小虎1',amount1: '324',amount2: '1.9',amount3: 9}, {id: '4',name: '王小虎4',amount1: '621',amount2: '2.2',amount3: 17}, {id: '5',name: '王小虎5',amount1: '539',amount2: '4.1',amount3: 15}],mergeField: ['name','amount1'],//存储字段合并的行数spanMap: {},},};},methods: {handleSpanMethod,columnDrop () {const wrapperTr = document.querySelector('.el-table__header-wrapper tr')Sortable.create(wrapperTr, {animation: 180,delay: 0,onEnd: evt => {let value = this.colDataconst oldItem = value[evt.oldIndex]value.splice(evt.oldIndex, 1)value.splice(evt.newIndex, 0, oldItem)}})},init () {this.tableData.mergeField.forEach(item => {this.tableData.spanMap[item] = tagRowSpan(this.tableData.data, item);})}},computed: {needMergeCol () {return this.tableData.mergeField.map(item => {return this.colData.findIndex(col => col.prop === item)})}},mounted () {document.body.ondrop = function (event) {event.preventDefault(); //用于取消事件的默认行为,比如拒绝拖拽元素的默认行为;event.stopPropagation(); //用于阻止事件冒泡,避免出现多重事件响应}this.init()this.$nextTick(() => {this.columnDrop()})},
};
</script>
注意不支持行拖拽