svelte :更改 html 块内的变量值

aat*_*ikh 8 svelte sveltekit

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

{#each list as item, i}
    <div class="item">
        <Item  />
    </div>
{/each}
Run Code Online (Sandbox Code Playgroud)

如何增加 svelte 中每个块内某些条件的计数?

小智 7

{@const ...}你可以像这样使用块内部

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

{#each list as item, i}
    {#if somecondition}
       {@const count=++count}

    <!-- and use it after maybe as Item prop -->
    <div class="item">
        <Item {count} />
    </div>
    {#else}
     <div class="item">
        <Item {count} />
    </div>
   {/if}
{/each}
Run Code Online (Sandbox Code Playgroud)


Isa*_*rey 6

如果您需要增加实际count变量,您可以在标记中定义的回调中执行此操作<script>

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

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

如果您需要做的只是添加一些量count而不改变原始变量,您可以在大括号内这么说:

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

{#each list as item, i}
    <div class="item">
        {count + i}
        <Item />
    </div>
{/each}
Run Code Online (Sandbox Code Playgroud)


小智 0

您可以只在括号内使用 JS,例如{count + i}{count + 1}。或者在循环中您可以使用条件语句,例如{#if count > 1}. 你是这个意思吗?