苗条的模板:循环

了解如何使用Svelte模板中的循环

在Svelte模板中,您可以使用{#each}{/each}句法:

<script>
let goodDogs = ['Roger', 'Syd']
</script>

{#each goodDogs as goodDog} <li>{goodDog}</li> {/each}

如果您熟悉其他使用模板的框架,则其语法非常相似。

您可以使用以下方法获取迭代的索引:

<script>
let goodDogs = ['Roger', 'Syd']
</script>

{#each goodDogs as goodDog, index} <li>{index}: {goodDog}</li> {/each}

(索引从0开始)

动态编辑列表中的删除和添加元素时,应始终在列表中传递标识符,以防止出现问题。

您可以使用以下语法进行操作:

<script>
let goodDogs = ['Roger', 'Syd']
</script>

{#each goodDogs as goodDog (goodDog)} <li>{goodDog}</li> {/each}

<!-- with the index --> {#each goodDogs as goodDog, index (goodDog)} <li>{goodDog}</li> {/each}

您也可以传递一个对象,但是如果列表中每个元素都有唯一的标识符,则最好使用它:

<script>
let goodDogs = [
  { id: 1, name: 'Roger'},
  { id: 2, name: 'Syd'}
]
</script>

{#each goodDogs as goodDog (goodDog.id)} <li>{goodDog.name}</li> {/each}

<!-- with the index --> {#each goodDogs as goodDog, index (goodDog.id)} <li>{goodDog.name}</li> {/each}

免费下载我的苗条手册


更多精妙的教程: