Quasar v2(Vue) QTable实现可展开行嵌套选择功能问询
嵌套可展开行表格实现方案
问题说明
需要制作带元素选择嵌套功能的表格,目前无法添加更多可展开行,现有数据结构为父行包含childrens子数组。
解决步骤
1. 给父行添加展开状态字段
在你的数据结构中,为每个父行新增isExpanded字段,用于控制子行的显示/隐藏:
rows: [ { name: 'Договор 1234567890', isExpanded: false, // 控制展开状态的字段 childrens: [ { calories: 159, fat: 6.0, carbs: 24, protein: 4.0, sodium: 87, calcium: '14%', iron: '1%', }, { calories: 159, fat: 6.0, carbs: 24, protein: 4.0, sodium: 87, calcium: '14%', iron: '1%', } ] }, { name: 'Договор 1234', isExpanded: false, childrens: [ { calories: 159, fat: 6.0, carbs: 24, protein: 4.0, sodium: 87, calcium: '14%', iron: '1%', } ] } ]
2. 修改表格模板渲染逻辑
以Vue为例,调整模板实现父行点击切换展开状态,同时渲染所有子行:
<table> <thead> <tr> <th>合同名称</th> <th>热量</th> <th>脂肪</th> <th>碳水</th> <th>蛋白质</th> <th>钠</th> <th>钙</th> <th>铁</th> </tr> </thead> <tbody> <!-- 遍历父行 --> <tr v-for="(parentRow, pIndex) in rows" :key="pIndex" @click="parentRow.isExpanded = !parentRow.isExpanded"> <td>{{ parentRow.name }}</td> <td colspan="7"> <span>{{ parentRow.isExpanded ? '▼' : '▶' }}</span> 点击展开子项 </td> </tr> <!-- 遍历子行,仅当父行展开时显示 --> <tr v-for="(child, cIndex) in parentRow.childrens" :key="`${pIndex}-${cIndex}`" v-if="parentRow.isExpanded" > <td></td> <td>{{ child.calories }}</td> <td>{{ child.fat }}</td> <td>{{ child.carbs }}</td> <td>{{ child.protein }}</td> <td>{{ child.sodium }}</td> <td>{{ child.calcium }}</td> <td>{{ child.iron }}</td> </tr> </tbody> </table>
3. 样式优化(可选)
给子行添加缩进,让层级更清晰:
/* 子行首列缩进 */ tbody tr:nth-child(n+2) td:first-child { padding-left: 25px; } /* 父行点击效果 */ tbody tr:first-child { cursor: pointer; background-color: #f0f0f0; }
内容的提问来源于stack exchange,提问作者neluckoff
相关产品推荐
相关产品推荐

