在Salesforce LWC中如何用多维数组渲染含多rowspan的HTML表格
LWC嵌套数据表格渲染实现方案
我从Apex拉取了嵌套结构的数据(1个问题对应多个回复,1个回复对应多个操作),数据结构如下,需要渲染成带合并单元格的表格。之前尝试用rowspan或子表格都出现样式错位,求简洁可行的实现方式。
数据结构
[ { "questionId": 1, "responses": [ { "responseId": 11, "responseText": "lorem ipsum", "actions": [ { "actionId": 111, "actionTitle": "dummy title 1" }, { "actionId": 112, "actionTitle": "dummy title 2" } ] } ] }, { "questionId": 2, "responses": [ { "responseId": 22, "responseText": "lorem ipsum text 2", "actions": [ { "actionId": 221, "actionTitle": "dummy title 3" } ] }, { "responseId": 23, "responseText": "lorem ipsum text 3", "actions": [ { "actionId": 331, "actionTitle": "dummy title 4" } ] } ] } ]
实现方案
核心思路是提前计算每个问题、每个回复需要合并的行数(对应下属操作的总数),循环渲染时仅为第一个操作渲染问题/回复单元格并设置rowspan,后续操作跳过对应单元格,确保合并对齐。
1. LWC HTML模板
<template> <table class="data-table"> <thead> <tr> <th>问题ID</th> <th>回复内容</th> <th>操作标题</th> </tr> </thead> <tbody> <!-- 循环问题 --> <template for:each={processedData} for:item="question"> <!-- 循环回复 --> <template for:each={question.responses} for:item="response"> <!-- 循环操作 --> <template for:each={response.actions} for:item="action" for:index="actionIdx"> <tr key={action.actionId}> <!-- 仅第一个操作渲染问题单元格,合并行数为该问题总操作数 --> <td if:true={actionIdx===0 && response.isFirstResponse} rowspan={question.totalActions}> {question.questionId} </td> <!-- 仅第一个操作渲染回复单元格,合并行数为该回复的操作数 --> <td if:true={actionIdx===0} rowspan={response.actionCount}> {response.responseText} </td> <td>{action.actionTitle}</td> </tr> </template> </template> </template> </tbody> </table> </template>
2. LWC JavaScript控制器
import { LightningElement, wire } from 'lwc'; // 替换为你的Apex方法 import getQuestionData from '@salesforce/apex/QuestionController.getQuestionData'; export default class NestedDataTable extends LightningElement { processedData; @wire(getQuestionData) wiredQuestionData({ error, data }) { if (data) { // 预处理数据,计算合并所需的行数和标记 this.processedData = data.map(question => { let totalActions = 0; const processedResponses = question.responses.map((response, respIdx) => { const actionCount = response.actions.length; totalActions += actionCount; return { ...response, actionCount, isFirstResponse: respIdx === 0 }; }); return { ...question, responses: processedResponses, totalActions }; }); } else if (error) { console.error('数据获取失败:', error); } } }
3. LWC CSS样式
.data-table { width: 100%; border-collapse: collapse; } .data-table th, .data-table td { border: 1px solid #d8dde6; padding: 8px 12px; text-align: left; vertical-align: top; } .data-table th { background-color: #f4f6f9; font-weight: bold; }
内容的提问来源于stack exchange,提问作者user21161667
相关产品推荐
相关产品推荐

