SvelteKit按分组展示API数据的实现问题求助
在SvelteKit中实现API数据分组表格展示
步骤1:在+page.ts中完成数据分组逻辑
先从API获取原始数据,再用数组reduce方法按指定字段(比如group)将数据整理为「分组名-对应数据集」的键值对结构:
// +page.ts export async function load({ fetch }) { // 调用你的API接口,替换为实际地址 const res = await fetch('/api/your-data-source'); const rawData = await res.json(); // 按数据中的分组字段(这里用group为例)分组,替换为你实际的分组标识字段 const groupedData = rawData.reduce((acc: Record<string, any[]>, item) => { const groupKey = item.group; if (!acc[groupKey]) acc[groupKey] = []; acc[groupKey].push(item); return acc; }, {}); return { groupedData }; }
步骤2:在+page.svelte中渲染分组表格
拿到分组后的数据,遍历每个分组,为每个组生成独立表格,以分组名作为表格标题:
<!-- +page.svelte --> <script lang="ts"> export let data; const { groupedData } = data; </script> <!-- 遍历所有分组 --> {#each Object.entries(groupedData) as [groupName, items]} <div class="group-table-wrapper"> <h2>Group {groupName}</h2> <table> <thead> <tr> <!-- 替换为你的数据列标题 --> <th>名称</th> <th>数值</th> <th>状态</th> </tr> </thead> <tbody> {#each items as item} <tr> <!-- 替换为你的实际数据字段 --> <td>{item.name}</td> <td>{item.value}</td> <td>{item.status || '未设置'}</td> </tr> {/each} </tbody> </table> </div> {:else} <p>暂无数据可展示</p> {/each} <style> .group-table-wrapper { margin: 2rem 0; } table { border-collapse: collapse; width: 100%; } th, td { border: 1px solid #e2e2e2; padding: 0.75rem; text-align: left; } th { background-color: #f8f8f8; } </style>
可选优化
如果需要对分组排序,比如按分组名称字母顺序排列,可以在+page.ts中添加排序逻辑:
// 在+page.ts的return前添加 const sortedGroups = Object.entries(groupedData).sort((a, b) => a[0].localeCompare(b[0])); return { sortedGroups };
之后在Svelte组件中遍历sortedGroups即可。
内容的提问来源于stack exchange,提问作者neuryzonso
相关产品推荐
相关产品推荐

