更新并显示#each块内的计数器变量值



我很难解决一个相对简单的问题。我被斯韦尔特的反应特点弄糊涂了。

在#每个块内,我需要更新并显示递增的"0"的值;计数器";在每次迭代之后。不幸的是,传入计数器变量会将所有迭代值更新为最新计数。

有没有办法";烘烤";变量的值输入到每个迭代中,而不是它们只引用变量?

<!-- the console log shows the desired result instead of the "6" value for every iteration -->
<script>
let arr = ["a","b","c","d","e","f"];
let counter = 0
let increment = ()=>{
counter++
console.log(counter)
return ""
}
const getCount = counter
</script>
{#each arr as item,i}
<p>
{item} -> {counter}
</p>
{increment()}
{/each}
<!-- I cannot use the "i"  since in my actual code I have #if blocks within the #each blocks which can either increment the counter or reset the counter.-->

显示问题的Svelte REPL。

有什么想法吗?

修改#each中的状态不是一个好主意,如Geoff Rich这可能会导致意想不到的行为。

当您生成数据时,应该将每个项与适当的索引相关联,然后简单地绑定到包含所述索引的属性。

最新更新