项目场景:
需求:不仅仅是左侧列的合并还有中间以及尾部列单元格的合并,饿了么官方目前只有起始列的合并案例
实现效果如图所示:>>>
合并行-列的代码封装:
提示:这里描述项目中遇到的问题:
例如:数据传输过程中数据不时出现丢失的情况,偶尔会丢失一部分数据
APP 中接收数据代码:
export const mergeCol =({
condition,
colIndex,
isBefore = true,
data = []
}) => {
let mergeArr = []
let objSpanMethod = ({
rowIndex, columnIndex }) => {
let condi = isBefore? columnIndex < colIndex : columnIndex > colIndex
if(condi) {
const rowspan =mergeArr[rowIndex]
const colspan rowspa> 0 ? 1: 0
return {
rowspan,
colspan
}
}
}
/*********************************/
let collectMergeLine = () => {
let collectArr =[1]
let collectPos =0
for(let i=1; data.length; i++) {
if (condition(i, data[i])) {
collectArr[collectPos] += 1
collectArr.push(0)
} else {
collectArr.push(1)
collectPos = i
}
}
console.1og(collectArr)
mergeArr = collectArr
}
return {
mergeArr, objSpanMethod. collectMergeline }
/**********************************/
/*合併表格單元格
* @param {array} colsIndex合併行索引
*/
export class mergeTableCol {
constructor(colsIndex) {
this.colsIndex = colsIndex
this.mergeArr =[]
}
objSpanMethod({
rowIndex, columnIndex }) {
let condi = this.colsIndex.includes(columnIndex)
if (condi) {
const rowspan = this. mergeArr[rowIndex]
const colspan =rowspan > 0 ? 1 : 0
return {
rowspan,
colspan
}
}
}
/*********************************/
/**
*收集合併行
*@param {function} condition條件返回true或false
*@param {array} data表格數據
*/
collectMergeLine(condition, data) {
let collectArr = [1]
let collectPos = 0
for(let i = 1; i < data.length; i++) {
if(condition(i, data[i])) {
collectArr[collectPos] +=1
collectArr.push(0)
} else {
collectArr.push(1)
collectPos = i
}
}
this.mergeArr = collectArr
return collectArr
}
}
在组件中引用该文件:
在需要此需求的页面组件引入此文件>>>
然后在表格标签上(v-bind)绑定(:span-method=“objSpanMethod”)函数!>>>
导入对应的函数>>>
methods:{
//表格合并处理
mergeCell(arr) {
this.mergeFn = new mergeTableCol(arr)
if(this.tableData.length > 0 ) {
this.collectMergeLine()
}
},
objSpanMethod(tableParams) {
if(this.mergeFn.objSpanMethod) {
return this.mergeFn.objSpanMethod(tableParams)
}
},
collectMergeLine(data = this.tableData) {
if(this.mergeFn.collectMergeLine) {
//判断渲染的数据id是否一致,合并条件
let condition = i=> data[i].id == data[i-1].id
//第一个参数是条件,返回true或false
this.mergeArr = this.mergeFn.collectMergeLine(condition, data)
}
},
请求到数据后,将需要合并的列,存入到数组中,然后将数组传递到megerCell函数中去做处理。>>>