循环
约 267 字小于 1 分钟
2026-09-20
我们使用 #each 来循环渲染一个数组,和 vue 的 v-for 类似。
不过他的 key 是使用 () 来包裹的,而不是 v-for 的 :key。
当然如果你的循环,永远不会导致界面的重绘,那么你可以不写 key,但是如果你的循环是动态的,那么你最好还是写上 key。
<script lang="ts">
const form = $state([
{ title: 'Step 1', id: 1 },
{ title: 'Step 2', id: 2 },
{ title: 'Step 3', id: 3 }
]);
</script>
{#snippet formStep({ title, id }: { title: string; id: number })}
<article>
<h2>{title}</h2>
<p>This is a form step with ID: {id}.</p>
</article>
{/snippet}
{#each form as item (item.id)}
{@render formStep(item)}
{/each}而且他还有一个更加强大的功能,他的循环支持对象解构
<script lang="ts">
const form = $state([
{ title: 'Step 1', id: 1 },
{ title: 'Step 2', id: 2 },
{ title: 'Step 3', id: 3 }
]);
</script>
{#each form as { title, id } (id)}
{@render formStep({ title, id })}
{/each}那么如何在循环中获取索引值呢, 只需要在取值的后面使用逗号再分割一下, 下一个就是索引值
{#each form as { title, id },index (id)}
{@render formStep({ title, id })}
{/each}