Skip to main content

{#each ...}

{#each expression as name}...{/each}
{#each expression as name, index}...{/each}

可以使用 each 块对值进行迭代。所讨论的值可以是数组、类似数组的对象(即具有 length 属性的任何内容)或可迭代对象(如 MapSet) — 换句话说,任何可以与 Array.from 一起使用的内容。

¥Iterating over values can be done with an each block. The values in question can be arrays, array-like objects (i.e. anything with a length property), or iterables like Map and Set — in other words, anything that can be used with Array.from.

<h1>Shopping list</h1>
<ul>
	{#each items as item}
		<li>{item.name} x {item.qty}</li>
	{/each}
</ul>

每个块还可以指定一个索引,相当于 array.map(...) 回调中的第二个参数:

¥An each block can also specify an index, equivalent to the second argument in an array.map(...) callback:

{#each items as item, i}
	<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}

为 each 块加键(Keyed each blocks)

¥Keyed each blocks

{#each expression as name (key)}...{/each}
{#each expression as name, index (key)}...{/each}

如果提供了键表达式(必须唯一地标识每个列表项),Svelte 将在数据更改时使用它来区分列表,而不是在末尾添加或删除项目。键可以是任何对象,但建议使用字符串和数字,因为它们允许在对象本身更改时保留身份。

¥If a key expression is provided — which must uniquely identify each list item — Svelte will use it to diff the list when data changes, rather than adding or removing items at the end. The key can be any object, but strings and numbers are recommended since they allow identity to persist when the objects themselves change.

{#each items as item (item.id)}
	<li>{item.name} x {item.qty}</li>
{/each}

<!-- or with additional index value -->
{#each items as item, i (item.id)}
	<li>{i + 1}: {item.name} x {item.qty}</li>
{/each}

你可以在每个块中自由使用解构和剩余模式。

¥You can freely use destructuring and rest patterns in each blocks.

{#each items as { id, name, qty }, i (id)}
	<li>{i + 1}: {name} x {qty}</li>
{/each}

{#each objects as { id, ...rest }}
	<li><span>{id}</span><MyComponent {...rest} /></li>
{/each}

{#each items as [id, ...rest]}
	<li><span>{id}</span><MyComponent values={rest} /></li>
{/each}

每个块都没有项目(Each blocks without an item)

¥Each blocks without an item

{#each expression}...{/each}
{#each expression, index}...{/each}

如果你只想渲染 n 次,则可以省略 as 部分(demo):

¥In case you just want to render something n times, you can omit the as part (demo):

<div class="chess-board">
	{#each { length: 8 }, rank}
		{#each { length: 8 }, file}
			<div class:black={(rank + file) % 2 === 1}></div>
		{/each}
	{/each}
</div>

else 块(Else blocks)

¥Else blocks

{#each expression as name}...{:else}...{/each}

每个块还可以有一个 {:else} 子句,如果列表为空,则会渲染该子句。

¥An each block can also have an {:else} clause, which is rendered if the list is empty.

{#each todos as todo}
	<p>{todo.text}</p>
{:else}
	<p>No tasks today!</p>
{/each}
上一页 下一页