Merge branch 'master' of https://git.nuttyreading.com/wangjinlei/tougao_web into Editorial-Board
This commit is contained in:
102
src/common/js/TableUtils.js
Normal file
102
src/common/js/TableUtils.js
Normal file
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* 表格数据处理工具
|
||||
*/
|
||||
export const TableUtils = {
|
||||
/**
|
||||
* 判断是否为表头行
|
||||
* @param {number} rowIndex
|
||||
* @param {Array} table
|
||||
*/
|
||||
isHeaderRow(rowIndex, table) {
|
||||
if (!table || table.length === 0) return false;
|
||||
const head = table[0];
|
||||
// 健壮性检查:确保第一行第一个单元格存在且有rowspan
|
||||
const headerSpan = (head && head[0] && head[0].rowspan) ? head[0].rowspan : 1;
|
||||
return rowIndex < headerSpan;
|
||||
},
|
||||
|
||||
/**
|
||||
* 拆分表头和表体
|
||||
*/
|
||||
splitTable(tableList) {
|
||||
if (!Array.isArray(tableList) || tableList.length === 0) {
|
||||
return { header: [], content: [] };
|
||||
}
|
||||
|
||||
const header = [];
|
||||
const content = [];
|
||||
let cellIdCounter = 0;
|
||||
|
||||
tableList.forEach((row, rowIndex) => {
|
||||
if (Array.isArray(row)) {
|
||||
row.forEach((cell) => {
|
||||
if (cell && typeof cell === 'object') {
|
||||
cell.cellId = `cell-${cellIdCounter++}`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (this.isHeaderRow(rowIndex, tableList)) {
|
||||
header.push(row);
|
||||
} else {
|
||||
content.push(row);
|
||||
}
|
||||
});
|
||||
|
||||
return { header, content };
|
||||
},
|
||||
|
||||
/**
|
||||
* 处理合并单元格后的逻辑行 ID(用于斑马纹等)
|
||||
*/
|
||||
addRowIdToData(content) {
|
||||
if (!content || content.length === 0) return { rowData: [], rowIds: [] };
|
||||
|
||||
const data = JSON.parse(JSON.stringify(content));
|
||||
const rowIdMap = {};
|
||||
const usedRows = new Set();
|
||||
let idCounter = 0;
|
||||
|
||||
// 1. 建立逻辑行映射
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
if (usedRows.has(i)) continue;
|
||||
|
||||
const rowId = `row-${idCounter++}`;
|
||||
rowIdMap[i] = rowId;
|
||||
usedRows.add(i);
|
||||
|
||||
const row = data[i];
|
||||
for (let j = 0; j < row.length; j++) {
|
||||
const cell = row[j];
|
||||
if (cell && cell.rowspan > 1) {
|
||||
for (let k = 1; k < cell.rowspan; k++) {
|
||||
const nextRowIndex = i + k;
|
||||
if (nextRowIndex < data.length && !rowIdMap[nextRowIndex]) {
|
||||
rowIdMap[nextRowIndex] = rowId;
|
||||
usedRows.add(nextRowIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 注入 rowId 并提取唯一 ID 列表
|
||||
const seenIds = [];
|
||||
data.forEach((row, i) => {
|
||||
const rowId = rowIdMap[i];
|
||||
row.rowId = rowId; // 直接赋值给行对象
|
||||
row.forEach(cell => {
|
||||
if (cell) cell.rowId = rowId;
|
||||
});
|
||||
|
||||
if (rowId && !seenIds.includes(rowId)) {
|
||||
seenIds.push(rowId);
|
||||
}
|
||||
});
|
||||
|
||||
// 取奇数或偶数 ID 用于斑马纹(根据你的需求 index % 2 === 0)
|
||||
const rowIds = seenIds.filter((_, index) => index % 2 === 0);
|
||||
|
||||
return { rowData: data, rowIds };
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user