SAPUI5 Responsive Table多选模式下加载数据时如何设置默认选中记录
可行实现方案
方案1:通过模型绑定实现自动选中(优先推荐)
这是符合SAPUI5 MVVM设计的最佳实践,无需手动操作控件实例,选中状态和模型数据自动同步:
- 给你的
ProductCollection数据集的每个条目新增布尔类型的选中标识字段,比如命名为selected,初始化数据时将需要预先选中的条目对应selected字段设为true - 修改表格行项的配置,给
ColumnListItem添加selected属性绑定该字段:
<ColumnListItem selected="{selected}"> <cells> <!-- 原有cells内容不变 --> <ObjectIdentifier title="{Name}" text="{ProductId}"/> <Text text="{SupplierName}" /> <Text text="{Width} x {Depth} x {Height} {DimUnit}" /> </cells> </ColumnListItem>
配置完成后,表格加载数据时会自动匹配模型的selected字段值,自动勾选对应行,后续选中状态变化也会自动同步到模型中。
方案2:表格数据加载完成后手动调用API设置选中
如果不方便修改原数据集结构,可以监听表格数据加载完成事件后手动设置选中项:
- 给Table控件添加
updateFinished事件绑定,该事件会在表格绑定的所有数据加载渲染完成后触发:
<Table id="idProductsTable" inset="false" mode="MultiSelect" alternateRowColors="true" updateFinished=".onTableUpdateFinished" items="{ path: '/ProductCollection', sorter: { path: 'Name' } }"> <!-- 原有表格内容不变 --> </Table>
- 在控制器中添加对应事件处理方法,遍历行项匹配需要预先选中的记录:
onTableUpdateFinished: function (oEvent) { const oTable = this.byId("idProductsTable"); // 替换为你实际需要预先选中的记录唯一标识列表,比如ProductId const aPreSelectedProductIds = ["1001", "1003", "1005"]; oTable.getItems().forEach(oItem => { const sCurrentProductId = oItem.getBindingContext().getProperty("ProductId"); if (aPreSelectedProductIds.includes(sCurrentProductId)) { oTable.setSelectedItem(oItem, true); } }); }
注意事项
- 如果表格开启了分页加载,方案2仅会对当前页的记录生效,跨页选中需求建议使用方案1实现
- 不要在页面初始化的
onInit/onAfterRendering生命周期中直接调用选中API,此时表格数据可能还未请求渲染完成,会导致设置不生效
内容的提问来源于stack exchange,提问作者tarzanbappa
相关产品推荐
相关产品推荐

