【问题标题】:Break iteration (each) in Svelte?在 Svelte 中中断迭代(每个)?
【发布时间】:2019-10-17 00:28:35
【问题描述】:

是否可以在 Svelte 中中断迭代或像 angular (ng-repeat="items in item | limitTo:4") 那样进行限制? 例如:

{#each items as item, i}
  ...
  {#if i > 4}
    {:break}  <--- break here
  {/if}
  ...
{/each}

【问题讨论】:

    标签: svelte


    【解决方案1】:

    没有{:break} 块,但您可以slice 在迭代之前取出数组中的前4 个元素。

    {#each items.slice(0, 4) as item, i} ... {/each}
    

    【讨论】:

      【解决方案2】:

      Svelte 目前没有用于中断或范围的特殊语法。 (here's a pending proposal) 一个常见的习惯用法是使用{length: N} 对象作为#each 参数,这通常比每次渲染都创建新数组执行得更好。

      {#each {length: 4} as _, i} {items[i]} {/each}

      以下是其他一些有效的模式:

      <script>
          let items = ['a', 'b', 'c', 'd', 'e'];
          $: filteredItems = items.slice(0, 4);
          const filterItems = (i) => i.slice(0, 4);
      </script>
      
      <div>
          {#each {length: 4} as _, i}
              {items[i]}
          {/each}
      </div>
      <div>
          {#each items.slice(0, 4) as item}
              {item}
          {/each}
      </div>
      <div>
          {#each filteredItems as item}
              {item}
          {/each}
      </div>
      <div>
          {#each filterItems(items) as item}
              {item}
          {/each}
      </div>
      

      【讨论】:

        【解决方案3】:

        我只是使用{#each myItems as item}{#if yourtruevalue} {item} {/if} {/each} 我不知道性能影响,但它非常简单。如果yourtruevalue 为真——无论该项目的渲染条件是什么——它都会渲染,如果不是则跳过该项目。

        【讨论】:

          猜你喜欢
          • 2019-11-10
          • 2021-08-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-09
          • 2022-01-24
          相关资源
          最近更新 更多