svelte : change variable value inside html block

Viewed 1432
<script>
    let count=0;
</script>

{#each list as item, i}
    <div class="item">
        <Item  />
    </div>
{/each}

How do I increment the count on some condition inside each block in svelte?

2 Answers

If you need to increment the actual count variable, you can do so in a callback defined in your <script> tag:

<script>
    let count = 0;
    const increment = () => count++;
</script>

{#each list as item, i}
    <div class="item">
        <!-- Use increment() somewhere in here -->
        <Item />
    </div>
{/each}

If all you need to do is add some amount to count without mutating the original variable, you can just say so within braces:

<script>
    let count = 0;
</script>

{#each list as item, i}
    <div class="item">
        {count + i}
        <Item />
    </div>
{/each}

You can just use JS within brackets, such as {count + i} or {count + 1}. Or wihtin the loop you could use a conditional statement like {#if count > 1}. Is that what you mean?

Related