Blazor WASM实现两行列表分页展示(每行5项)
Blazor WASM实现两行5条数据的分页展示
1. 准备数据与分页变量
先定义数据模型,再在组件内声明数据集合和分页相关变量:
public class Item { public int Id { get; set; } public string Name { get; set; } = string.Empty; } // 组件内变量 private List<Item> allItems = new(); private List<Item> currentPageItems = new(); private int currentPage = 1; // 每页显示10条(两行×5条) private int pageSize = 10; // 计算总页数 private int totalPages => (int)Math.Ceiling((double)allItems.Count / pageSize);
初始化15条模拟数据:
protected override void OnInitialized() { allItems = Enumerable.Range(1, 15).Select(i => new Item { Id = i, Name = $"数据项 {i}" }).ToList(); LoadCurrentPage(); }
2. 实现分页加载逻辑
写一个方法根据当前页码截取对应数据:
private void LoadCurrentPage() { currentPageItems = allItems.Skip((currentPage - 1) * pageSize).Take(pageSize).ToList(); }
3. 分页按钮交互逻辑
实现上一页、下一页的点击事件:
private void PreviousPage() { if (currentPage > 1) { currentPage--; LoadCurrentPage(); } } private void NextPage() { if (currentPage < totalPages) { currentPage++; LoadCurrentPage(); } }
4. 渲染UI布局
用flex布局实现每行5条的展示,搭配分页控件:
<style> .item-grid { display: flex; flex-wrap: wrap; gap: 1rem; margin-bottom: 2rem; padding: 0 1rem; } .item-card { flex: 0 0 calc(20% - 0.8rem); border: 1px solid #e0e0e0; border-radius: 8px; padding: 1.2rem; background-color: #fff; } .pagination-bar { display: flex; align-items: center; justify-content: center; gap: 1.5rem; } .pagination-btn { padding: 0.5rem 1.2rem; border: none; border-radius: 6px; background-color: #007bff; color: white; cursor: pointer; } .pagination-btn:disabled { background-color: #6c757d; cursor: not-allowed; } </style> <div class="item-grid"> @foreach (var item in currentPageItems) { <div class="item-card"> <h5>@item.Name</h5> <p>ID: @item.Id</p> </div> } </div> <div class="pagination-bar"> <button class="pagination-btn" @onclick="PreviousPage" disabled="@(currentPage == 1)">上一页</button> <span>第 @currentPage 页 / 共 @totalPages 页</span> <button class="pagination-btn" @onclick="NextPage" disabled="@(currentPage == totalPages)">下一页</button> </div>
效果说明
- 第一页显示10条数据,自动排成两行(每行5条);第二页显示剩余的5条数据。
- 分页按钮会根据当前页码自动禁用,避免无效操作。
内容的提问来源于stack exchange,提问作者Abdulsalam Elsharif
相关产品推荐
相关产品推荐

