大家好,我是睡不醒的春春,突破自己,实现第一次发文
在掘金逛了很久,一直都有发文的想法,最近闲来无事整理一下自己在开发中遇到的问题,解决的同时借鉴了很多优秀的程序猿们的想法
单纯的为了记录遇到的问题及解决方法,方便以后遇到同样的问题可以参考
<template>
<el-table
:data="tableData"
border
:span-method="spanMethod"
>
<el-table-column
prop="id"
label="ID"
>
<template slot-scope="scope">
<span>{{ scope.row.id }}</span>
<el-button @click="appendChild(scope.row, scope.$index)">增加</el-button>
</template>
</el-table-column>
<el-table-column
prop="name"
label="姓名"
width="180"
></el-table-column>
<el-table-column
prop="amount"
label="数值"
width="180"
></el-table-column>
</el-table>
</template>
<script>
export default {
data () {
return {
tableData:[
{
id: '12987122',
name: '王小虎',
amount: '234',
},
{
id: '12987122',
name: '王小虎',
amount: '234',
},
{
id: '12987122',
name: '王小虎',
amount: '234',
},
{
id: '12987166',
name: '王大虎',
amount: '234',
},
{
id: '12987166',
name: '王大虎',
amount: '234',
},
],
spanData: [], // 遍历数据时,根据相同的标识区存储记录
pos: 0, // 数组索引
}
},
mounted () {
this.getSpanData()
},
methods: {
spanMethod ({ row, column, rowIndex, columnIndex }) {
if (columnIndex === 0) {
const _row = this.spanData[rowIndex]
const _col = _row > 0 ? 1 : 0
return {
rowspan: _row,
colspan: _col,
}
}
},
getSpanData () {
const data = this.tableData
this.spanData = [] // 每次调用清空,防止数据错乱
for (let i = 0; i < data.length; i++) {
if (i == 0) {
this.spanData.push(1)
this.pos = 0
} else {
// 根据条件判断是否相同
if (data[i].id == data[i-1].id) {
this.spanData[this.pos] += 1
this.spanData.push(0)
} else {
this.pos = i
this.spanData.push(1)
}
}
}
},
// 合并单元格后插入数据
appendChild (row, index) {
// 表格数据--合并项条件保持一致
const obj = {
id: row.id,
name: '',
amount: '',
}
// 新数据插入的下标
const idx = this.spanData.slice(0, index + 1).reduce((prev, curr) => {
return prev + curr
})
this.tableData.splice(idx, 0, obj) // 插入数据
// 重新调用合并单元格
this.getSpanData()
}
}
}
</script>