16
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Svelteでn回ループ表示させたい時の書き方を考える

Last updated at Posted at 2023-09-05

はじめに

Svelteでn回ループ表示させたい場合の書き方について考えてみます。

バージョン

Svelte 4.2.0

一般的な書き方

Svelteでn回ループ表示させたい場合は以下のように書くのが一般的だと思います。
これでも充分動くので良いですが、せっかくSvelteの構文で書いているのに少し冗長な気がします。
いくつか別のアプローチを考えてみましょう。

例:1

{#each Array(n) as _, i}
  <p>{i}</p>
{/each}

例:2

{#each { length: n } as _, i}
  <p>{i}</p>
{/each}

アプローチ1 rangeヘルパーメソッドを作成する

rangeヘルパーメソッドを作成します。
別途メソッドを用意する必要はありますが、スッキリと読みやすい印象です。

helper.ts
export function* range(start:number, end:number) {
  for (let i = start; i < end; i++) {
    yield i;
  }
}
App.svelte
<script>
 import { range } from './helper.ts';
</script>

{#each range(0,5) as i}
  <p>{i}</p>
{/each}

アプローチ2 <Range>コンポーネントを作成する

先程作ったrangeヘルパーメソッドをwrapした<Range>コンポーネントを作成します。
start,endのプロパティでわかりやすいですし、i(index)も不要であれば呼び出し側で省略できます。
よりシンプルでわかりやすい印象です。
ただ、{#each}を隠蔽しているのでループしていることが理解しづらいかもしれません。
(<Loop>コンポーネントのほうがわかりやすい? :thinking: )

REPL: https://svelte.dev/repl/4312129c2d3c4cfdbbf9631234009eb3?version=4.2.0

Range.svelte
<script lang="ts">
  export let start: number;
  export let end: number;

  function* range(start: number, end: number) {
    for (let i = start; i < end; i++) {
      yield i;
    }
  }
</script>

{#each range(start, end) as i (i)}
  <slot {i} />
{/each}
App.svelte
<script lang="ts">
    import Range from "./Range.svelte"
</script>

<Range start={0} end={5} let:i>
    <p>{i}</p>
</Range>

さいごに

Svelteでn回ループ表示させたい時のいくつかのアプローチを考えてみました。
是非参考にしてみてください。

実はSvelteで{#range ...}構文を追加するissueが立っています。
{#range ...}が追加されればこれらのアプローチは不要になるので追加されてほしいですね。
2019年に作成以来、動きがないのでいつ追加されるかは不明ですが、Svelte5に期待しましょう。

16
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?