Vue element-ui 动态合并行列
2020-03-15 本文已影响0人
Puccino
后端返回一个 list ,先根据 list 处理为表格,同时想要实现 word 里面那种任意合并单元格的样式,查了好多地方。效果如下:
效果
即根据数据内容进行动态合并,思路是先将 list 数据处理为 对象 形式:
var recv = [
['1','1','3','4','5'],
['6','7','8','9','10'],
['11','12','13','9','15'],
['11','17','18','19','19']]
var tableKey = []
var tableData = []
var obj = new Object()
recv[0].forEach((item,index,array)=>{
tableKey.push({value:'col'+index, name:item})
})
recv.forEach((item,index,array)=>{
item.forEach((iitem,iindex,iarray)=>{
obj['col'+iindex]=iitem
})
tableData.push(obj)
// 清空对象
obj = new Object()
})
这样表头数据和表格数据就会装载为:
tableData = [
{"value":"col0","name":"1"},
{"value":"col1","name":"1"},
{"value":"col2","name":"3"},
{"value":"col3","name":"4"},
{"value":"col4","name":"5"}]
tableData = [
{"col0":"1","col1":"1","col2":"3","col3":"4","col4":"5"},
{"col0":"6","col1":"7","col2":"8","col3":"9","col4":"10"},
{"col0":"11","col1":"12","col2":"13","col3":"9","col4":"15"},
{"col0":"11","col1":"17","col2":"18","col3":"19","col4":"19"}
]
最后在组件中进行处理:
export default{
name: 'table',
data(){
return{
// 行合并数据和列合并数据
spanRowArrs:[],
spanColArrs:[],
tableKey,
tableData
}
},
created(){
// 挂载函数
this.getSpanArr(this.tableData)
this.getRowSpanArr(this.tableData)
},
methods:{
// 1 处理纵向数据
getSpanArr(data) {
var spanArr=[];
for (var prop in data[0]){
for (var i = 0; i < data.length; i++) {
if (i === 0) {
spanArr.push(1);
this.pos = 0;
} else {
if (data[i][prop] === data[i - 1][prop]) {
spanArr[this.pos] += 1;
spanArr.push(0);
} else {
spanArr.push(1);
this.pos = i;
}
}
}
this.spanRowArrs.push(spanArr)
spanArr = []
}
},
// 2. 处理横向数据
getRowSpanArr(data){
var spanArr=[];
var keyArr = Object.keys(data[0]);
for(var i = 0 ; i < data.length; i++){
for(var j = 0; j< keyArr.length; j++){
if (j === 0){
spanArr.push(1);
this.pos=0;
}else{
if(data[i][keyArr[j]] === data[i][keyArr[j-1]]){
spanArr[this.pos] += 1;
spanArr.push(0);
} else {
spanArr.push(1);
this.pos = j;
}
}
}
this.spanColArrs.push(spanArr)
spanArr = []
}
},
// 3 返回合并数
spanMethod({ row, column, rowIndex, columnIndex }){
if (columnIndex >= 0) {
const _row = this.spanRowArrs[columnIndex][rowIndex];
const _col = this.spanColArrs[rowIndex][columnIndex];
//const _col = _row > 0 ? 1 : 0;
return {
rowspan: _row,
colspan: _col
}
}
}
}
}