ElementUI el-table 动态合并单元格

一、最上方操作栏包括:

  1. 添加批次:点击在批次队尾添加一个新批次;
  2. 批次操作Tag(展示格式为批次名称(数量)):点击批次Tag可定位至表格对应批次,点击×删除批次;
  3. 表格数据操作栏

二、下方是对批次的校验;

三、批次与表格数据是双向的,通过批次操作栏操作批次会引起表格数据变化,添加、删除、在表格中修改批次数量也会引起批次操作栏的变化

<template>
    <el-container>
        <el-header style="height: 52px;">
            <div>
                <el-button type="success" plain size="small" :disabled="addPcDisabled" @click="addPc">添加批次</el-button>
                <el-tag v-for="(li, index) in batchList" :key="index" :closable="closable" @click="pcScrollIntoView(index+1)" @close="delPc(index)">{{ '批次'+(index+1)+' ('+li+')' }}</el-tag>
            </div>
            <div style="text-align: right;">
                <el-button type="success" plain size="small" @click="addRow">添加</el-button>
                <el-button type="danger" plain size="small" :disabled="batchDelDisabled" @click="batchDelRow">批量删除</el-button>
            </div>
        </el-header>
        <el-main>
            <el-table ref="table" :data="showDatas" :span-method="mergeRowByPc" border highlight-current-row highlight-selection-row style="width: 100%;" @selection-change="tableSelectionChange">
                <el-table-column type="index" width="50" align="center" class-name="no-interact"></el-table-column>
                <el-table-column prop="pc" label="批次" min-width="120" align="center" class-name="vertical-top no-interact">
                    <template slot-scope="scope">
                        <div>
                            <p :id="'pc'+scope.row.pc">{{ '批次'+scope.row.pc }}</p>
                            <el-input-number v-model="batchList[String(scope.row.pc-1)]" :min="0" step-strictly controls-position="right" @change="(val, old) => pcCountChange(scope.row.pc-1, val, old)"></el-input-number>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="name" label="姓名" min-width="120" align="center"></el-table-column>
                <el-table-column label="操作" min-width="40" align="center">
                    <template slot-scope="scope">
                        <i class="el-icon-delete" @click="delRow(scope.$index, scope.row.pc-1)"></i>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <el-footer>
            <el-button @click="cancelConfigOper">取消</el-button>
            <el-button type="primary" @click="saveConfigOper">保存</el-button>
        </el-footer>
    </el-container>
</template>
<script>
export default {
    data () {
        return {
            maxProduce: 4, //产线最大生产数量,即每个批次的最大数量
            dataSource: [],
            selectedDatas: [],
            batchList: [], //每个元素为每个批次的实际数量,数组元素相加的和等于dataSource的length
            total: 17
        }
    },
    computed: {
        addPcDisabled () { //表格不会显示批次数量为0的批次,操作批次数据时,平移数据大多平移至最后一个批次;如果batchList末尾有连续为0的批次,则下一次操作批次时,可能会导致表格显示和平移数据时出现问题;batchList为0的数据一定是添加批次操作出来的,因此添加过批次且添加批次没有数据时,禁止再添加批次
            return this.batchList.length>0&&this.batchList[this.batchList.length-1]===0;
        },
        closable () {
            return this.batchList.length>1;
        },
        batches () {
            let batches = {}, sum = 0;
            this.batchList.forEach((li, index) => {
                batches[String(index)] = {
                    startIndex: sum,
                    count: li
                };
                sum += li;
            });
            return batches;
        },
        showDatas () {
            let pc = '', data = {};
            return this.dataSource.map((li, index) => {
                pc = this.getPcNumber(index);
                data = this.batches[String(pc-1)];
                return Object.assign({
                    index: index,
                    pc: pc
                }, li, data);
            });
        },
        batchDelDisabled () {
            return this.selectedDatas.length===0;
        }
    },
    watch: {
        showDatas: {
            handler () {
                this.$nextTick(() => {
                    this.selectedDatas = []; //表格多选功能,仅用于批量删除表格行;表格数据发生变化时,批量删除用到的批次字段值可能发生变化,但变化却不能更新到selectedDatas中,因此表格展示发生变化时,立即清空selectedDatas
                    document.querySelectorAll('p[id*="pc"]').forEach(li => { //将批次定位id移至所属td,点击批次标签,滚动到对应批次的第一条表格数据
                        li.parentNode.parentNode.parentNode.setAttribute('id', li.id);
                        li.removeAttribute('id');
                    });
                });
            },
            deep: true
        }
    },
    methods: {
        show () {
            let result = this.getMaxDivide(), list = new Array(result.copies);
            list.fill(result.maxFactor);
            this.batchList = 'remainder' in result?list.concat([result.remainder]):list;
            for(let i=1; i<=this.total; i++) {
                this.dataSource.push({
                    name: i
                });
            }
        },
        mergeRowByPc ({ row, rowIndex, columnIndex }) { //表格合并单元格函数的判断条件,一定要关联表格合并单元格函数提供的参数,关联其他来源的变量,会导致不可预料的问题
            if(columnIndex===1) {
                return rowIndex===row.startIndex?[row.count, 1]:[0, 0];
            }
        },
        addRow () {
            if(this.batchList.length) {
                let orderList = this.dataSource.slice();
                orderList.sort((a, b) => b.name-a.name);
                this.$set(this.batchList, this.batchList.length-1, this.batchList[this.batchList.length-1]+1);
                this.dataSource.push({
                    name: orderList[0].name+1
                });
            } else {
                this.batchList.push(1);
                this.dataSource.push({
                    name: 1
                });
            }
        },
        delRow (index, pcIndex) {
            this.$confirm('确定删除吗?', '删除产品配置', {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                this.batchList[pcIndex]===1?this.batchList.splice(pcIndex, 1):this.$set(this.batchList, pcIndex, this.batchList[pcIndex]-1);
                this.dataSource.splice(index, 1);
            }).catch(() => {});
        },
        batchDelRow () {
            this.$confirm('确定删除选中的产品配置吗?', '批量删除产品配置', {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                let index = -1, pcIndex = -1, sum = 0;
                this.selectedDatas.forEach(li => {
                    //删除表格行的同时,还未被删除的选中元素的实际所属批次、batchList数组长度可能发生变化,在dataSource中的下标一定发生变化,,因此批量删除选中行时,要动态获取删除行的批次下标
                    index = this.showDatas.findIndex(d => d.name===li.name);
                    pcIndex = this.showDatas[index].pc-1;
                    this.batchList[pcIndex]===1?this.batchList.splice(pcIndex, 1):this.$set(this.batchList, pcIndex, this.batchList[pcIndex]-1);//操作数组某一元素,要用一定能引起vue数据更新的方式,不然视图可能不会更新
                    this.dataSource.splice(li.index-sum, 1);
                    sum++;
                });
            }).catch(() => {});
        },
        tableSelectionChange (val) {
            this.$refs.table.setCurrentRow(); //清除单选选中行
            this.selectedDatas = val;
        },
        pcCountChange (index, val, old) { //采用的是v-model双向绑定,触发到change事件,batchList数组元素已经被改变了,除非被改为0,否则不需要在函数中再操作被修改批次在batchList的值
            let number = Math.abs(val-old);
            if(val>old) { //增加批次生产数量
                if(this.batchList.length===1) { //只有一个批次,增加批次生产数量,直接在dataSource中添加数据
                    let orderList = this.dataSource.slice(), addDatas = [];
                    orderList.sort((a, b) => b.name-a.name);
                    for(let i=1; i<=number; i++) {
                        addDatas.push({
                            name: orderList[0].name+i
                        });
                    }
                    this.dataSource = this.dataSource.concat(addDatas);
                } else { //有多个批次
                    if(val>this.dataSource.length) { //将某一批次的数量修改至大于表格数据总数,那么只保留这一批次,并且在dataSource中添加比总数多出数量个数的数据
                        this.batchList = [val];
                        let orderList = this.dataSource.slice(), addDatas = [], len = val-this.dataSource.length;
                        orderList.sort((a, b) => b.name-a.name);
                        for(let i=1; i<=len; i++) {
                            addDatas.push({
                                name: orderList[0].name+i
                            });
                        }
                        this.dataSource = this.dataSource.concat(addDatas);
                    } else { //修改的批次数量小于等于表格数据总数,那么只是dataSource数据所属批次发生变化
                        let list = this.batchList.slice();
                        if(index===0) { //修改第一批次数量,从后面平移数据
                            while (number>0&&this.batchList.length>1) {
                                if(list[1]<=number) { //被平移数据的批次数量小于等于需要平移的数量,则平移数量减去被平移数据的批次数量,删除被平移数据的批次
                                    number -= list[1];
                                    list.splice(1, 1); //splice会导致数组长度发生变化,进而第一个元素一直发生变化,不需要手动操作下标
                                } else { //被平移数据的批次数量大于需要平移的数量,被平移批次数量减去平移数量,平移数量置为0
                                    list[1] -= number;
                                    number = 0;
                                }
                            }
                        } else if(index===this.batchList.length-1) { //修改最后一个批次数量,从前面平移数据
                            while (number>0&&this.batchList.length>1) { 
                                if(list[this.batchList.length-2]<=number) {
                                    number -= list[this.batchList.length-2];
                                    list.splice(this.batchList.length-2, 1); //splice会导致数组长度发生变化,进而最后一个元素和倒数第二个元素的下标也发生变化,不需要手动操作下标
                                } else {
                                    list[this.batchList.length-2] -= number;
                                    number = 0;
                                }
                            }
                        } else {//修改中间批次数量,从前后两端平移数据
                            let i = index+1; //先从后面平移数据,因为下一个批次的下标一直不会发生变化
                            while(number>0&&this.batchList.length>i&&Boolean(list[i])) { //添加批次会导致批次数量为0的批次存在,因此要判断批次数量是否为0
                                if(list[i]<=number) {
                                    number -= list[i];
                                    list.splice(i, 1);
                                } else {
                                    list[i] -= number;
                                    number = 0;
                                }
                            }
                            if(number>0) { //后面的数据不够,从前面平移,被修改批次现在实际变为最后一个批次
                                i = index-1;
                                while(number>0&&i>=0) {
                                    if(list[i]<=number) {
                                        number -= list[i];
                                        list.splice(i, 1); //splice会导致数组长度发生变化,进而前一个元素下标一直发生变化,需要手动操作下标
                                        i--;
                                    } else {
                                        list[i] -= number;
                                        number = 0;
                                    }
                                }
                            }
                        }
                        this.batchList = list;
                    }
                }
            } else { //减少批次生产数量
                if(this.batchList.length===1) { //只有一个批次
                    if(val===0) { //删除仅有的一个批次,则删除所有数据(清空dataSource)
                        this.batchList = [];
                        this.dataSource = [];
                    } else { //减少批次数量,将减少数量挪至下一个批次,dataSource不发生变化
                        this.batchList.push(number);
                    }
                } else { //多个批次
                    if(index===this.batchList.length-1) { //减少最后一个批次数量
                        if(val===0) { //删除最后一个批次,数据平移至倒数第二个批次中,dataSource不发生变化
                            this.batchList.pop(); //删除最后一个批次,数据长度发生变化,此时的最后一个元素即为pop前的倒数第二个元素
                            this.batchList[this.batchList.length-1] += number;
                        } else { //减少数量挪至下一个批次,dataSource不发生变化
                            this.batchList.push(number);
                        }
                    } else { //减少第一个和中间批次数量
                        if(val===0) { //删除批次,批次数据平移至最后一个批次,表格数据顺序发生变化
                            let datas = this.dataSource.splice(this.batches[String(index)].startIndex, number);
                            this.batchList.splice(index, 1);
                            this.batchList[this.batchList.length-1] += number;
                            this.dataSource = this.dataSource.concat(datas);
                        } else { //减少批次数量,将减少数量平移至最后一个批次,表格数据顺序发生变化
                            this.batchList[this.batchList.length-1] += number;
                            this.dataSource = this.dataSource.concat(this.dataSource.splice(this.batches[String(index)].startIndex+this.batches[String(index)].count, number));
                        }
                    }
                }
            }
        },
        addPc () {
            this.batchList.push(0);
        },
        delPc (index) { //删除批次,批次数据平移至最后一个批次,表格数据顺序发生变化;只有一个批次时禁止删除批次,一次不会存在被删除批次和数据平移批次为同一批次的情况
            let number = this.batchList[index], datas = this.dataSource.splice(this.batches[String(index)].startIndex, number);
            this.batchList.splice(index, 1);
            this.$set(this.batchList, this.batchList.length-1, this.batchList[this.batchList.length-1]+number);
            this.dataSource = this.dataSource.concat(datas);
        },
        pcScrollIntoView (number) { //点击批次标签,滚动到对应批次的第一个td
            this.batches[String(number-1)].count?this.$el.querySelector('#pc'+number).scrollIntoView():'';
        },
        cancelConfigOper () {
            this.$confirm('确定后您的更改将不会被保存, 确定取消配置吗?', '取消配置', {
                type: 'warning',
                confirmButtonText: '确定',
                cancelButtonText: '取消'
            }).then(() => {
                console.log('取消配置');
            }).catch(() => {});
        },
        saveConfigOper () {
            if(this.batchList.reduce((a, b) => a+b)===this.total) { //无论如何操作数据,数量都应等于合计数量
                let emputyPcList = [], overMaxProducePcList = [];
                this.batchList.forEach((li, index) => {
                    if(li===0) {
                        emputyPcList.push('批次'+(index+1)); //不可以存在生产数量为0的批次
                    } else if(li>this.maxProduce) {
                        overMaxProducePcList.push('批次'+(index+1)); //不可以存在生产数量大于产线最大生产数量的批次
                    }
                });
                if(emputyPcList.length>0&&overMaxProducePcList.length>0) {
                    this.$message.error(emputyPcList.join('、')+' 生产数量为0,请删除;'+overMaxProducePcList.join('、')+'生产数量超过产线生产数量,请修改。');
                } else if(emputyPcList.length>0) {
                    this.$message.error(emputyPcList.join('、')+' 生产数量为0,请删除。');
                } else if(overMaxProducePcList.length>0) {
                    this.$message.error(overMaxProducePcList.join('、')+'生产数量超过产线生产数量,请修改。');
                } else {
                    this.$confirm('确定保存吗?', '保存配置', {
                        type: 'warning',
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {
                        console.log('保存配置');
                    }).catch(() => {});
                }
            } else {
                this.$message.error('所有批次生产总数超过生产单合计数量,请修改。');
            }
        },
        getMaxDivide () {
            let result = {}, list = [];
            for(let i=1; i<=this.total; i++) {
                this.total%i===0?list.push(i):'';
            }
            list = list.filter(li => li<=this.maxProduce);
            list.sort((a, b) => b-a);
            if(list[0]===1 && this.total>1) { //合计数量为质数或者最大除数被最大生产数量过滤掉
                result = this.total<=this.maxProduce?{
                    maxFactor: this.total,
                    copies: 1
                }:{
                    maxFactor: this.maxProduce,
                    copies: Math.floor(this.total/this.maxProduce),
                    remainder: this.total%this.maxProduce
                };
            } else {
                result = {
                    maxFactor: list[0],
                    copies: this.total/list[0]
                };
            }
            return result;
        },
        getPcNumber (index) {
            let sum = 0, number = 0;
            for(let i=0; i<this.batchList.length; i++) {
                sum += this.batchList[i];
                if(index<sum) {
                    number = i+1;
                    break;
                }
            }
            return number;
        }
    },
    mounted () {
        this.show();
    }
}
</script>
<style scoped>
>>>.el-header {
    padding: 10px 20px;
    display: grid;
    grid-template-columns: auto 146px;
    column-gap: 10px;
}
/* 将表格固定在中间,始终显示上、方操作区域 */
>>>.el-main {
    height: calc(100vh - 130px);
    padding: 0 20px 10px 20px;
    overflow-y: auto;
}
>>>.el-footer {
    padding: 10px 20px;
    text-align: right;
}
>>>.el-tag {
    margin-left: 10px;
    cursor: pointer;
}
>>>.el-table .el-table__cell {
    padding: 5px 0;
}
/* 批次列内容顶端对齐,防止批次数量过多,刚滚动至批次时,看不到属于哪个批次 */
>>>.el-table td.vertical-top.el-table__cell {
    vertical-align: top;
}
/* 删除表格index列、批次列的单选样式和多选被选中样式 */
>>>.el-table--enable-row-hover .el-table__body tr:hover>td.no-interact.el-table__cell,
>>>.el-table__body tr.hover-row>td.no-interact.el-table__cell,
>>>.el-table__body tr.current-row>td.no-interact.el-table__cell,
>>>.el-table__body tr.selection-row>td.no-interact.el-table__cell {
    background-color: #FFF;
}
</style>

### 回答1: el-tableElementUI 中的表格组件,它提供了一些功能来合并单元格。下面是一个简单的示例: ```html <template> <el-table :data="tableData" border style="width: 100%"> <el-table-column prop="name" label="姓名"></el-table-column> <el-table-column prop="age" label="年龄"></el-table-column> <el-table-column prop="address" label="地址"></el-table-column> <el-table-column label="操作"> <template slot-scope="scope"> <el-button size="mini" @click="handleDelete(scope.$index)">删除</el-button> </template> </el-table-column> </el-table> </template> <script> export default { data() { return { tableData: [ { name: '张三', age: 18, address: '北京市海淀区' }, { name: '李四', age: 20, address: '上海市黄浦区' }, { name: '王五', age: 22, address: '广州市天河区' }, { name: '赵六', age: 24, address: '深圳市南山区' }, { name: '孙七', age: 26, address: '杭州市西湖区' } ] } }, methods: { handleDelete(index) { this.tableData.splice(index, 1) } } } </script> ``` 上面的代码中,我们通过使用 `<el-table-column>` 组件的 `prop` 属性来定义数据源中的每列数据。我们可以通过设置 `span-method` 属性为一个函数来定义合并单元格的规则。例如,我们想要将第一列相同的单元格合并成一个单元格,可以这样写: ```html <el-table :data="tableData" border style="width: 100%"> <el-table-column prop="name" label="姓名" :span-method="nameSpanMethod"></el-table-column> <el-table-column prop="age" label="年龄"></el-table-column> <el-table-column prop="address" label="地址"></el-table-column> <el-table-column label="操作"> <template slot-scope="scope"> <el-button size="mini" @click="handleDelete(scope.$index)">删除</el-button> </template> </el-table-column> </el-table> ``` 然后,在 Vue 实例中,我们定义 `nameSpanMethod` 方法来实现单元格的合并: ```js methods: { nameSpanMethod({ row, column, rowIndex, columnIndex }) { if (columnIndex === 0) { if (rowIndex === 0) { return { rowspan: this.tableData.length, colspan: 1 } } else { return { rowspan: 0, colspan: 0 } } } }, handleDelete(index) { this.tableData.splice(index, 1) } } ``` 在 `nameSpanMethod` 方法中,我们根据当前单元格的位置来判断是否需要进行合并。如果当前单元格是第一列的第一个单元格,我们就返回一个对象,其中 `rowspan` 属性表示需要合并的行数,`colspan` 属性表示需要合并的列数。如果不需要合并,则返回 `{ rowspan: 0, colspan: 0 }`,这样就不会对单元格进行合并。 这样就实现了 el-table 的单元格合并功能。 ### 回答2: el-table是一个基于Vue.js的表格组件,可以帮助我们快速构建数据展示的表格。在el-table合并单元格通常需要通过使用span-method属性来实现。 span-method属性是一个函数,用来指定合并单元格的规则。我们需要在这个函数中判断当前单元格是否需要合并,并返回需要合并的行数和列数。 通过以下步骤可以实现el-table的单元格合并: 1. 在el-table的<el-table-column>组件中设置span-method属性,将其指向我们自定义的函数。 2. 自定义一个函数,在使用el-table组件的父组件中定义。这个函数接收两个参数:row和column。row代表当前单元格所在的行对象,column代表当前单元格所在列对象。 3. 在自定义的函数中,我们可以根据需要判断是否要合并单元格。如果需要合并,就返回一个包含两个属性的对象:rowspan和colspan。rowspan代表要合并的行数,colspan代表要合并的列数。如果不需要合并,就返回一个没有任何属性的对象。 4. 最后,el-table会根据我们返回的对象,来对相应的单元格进行合并。 通过上述步骤,我们就可以实现在el-table合并单元格的功能。注意,这个函数可以根据具体的需求进行定制,可以根据单元格的内容、行号、列号等信息来判断是否需要合并单元格。 ### 回答3: el-tableElement UI中的一个表格组件,它提供了丰富的功能和易用的API来实现表格的展示和交互操作。在el-table合并单元格可以通过使用span-method属性来实现。 在el-table中,可以通过设置span-method属性来动态合并单元格。span-method属性是一个函数,它返回一个对象,对象中的属性设置了行合并和列合并的方式。具体的合并方式可以根据具体的需求来进行设置。 在span-method函数中,我们可以通过传入参数来获取当前行和当前列的数据,然后根据业务逻辑来判断是否需要合并单元格。如果需要合并单元格,我们可以返回一个对象,设置合并的行数和列数,如果不需要合并单元格,我们可以返回一个空对象。 具体的合并单元格的逻辑可以根据具体的需求来进行编写,比如我们可以根据某一列的值相同来合并单元格,或者根据某一列的值和下一行的值相同来合并单元格等等。 总之,利用el-table的span-method属性,我们可以很方便地实现单元格的合并操作,只需要根据具体的需求编写合适的合并逻辑即可。这样就可以在el-table中实现单元格的合并。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值