LoginSignup
2
1

More than 1 year has passed since last update.

はじめに

SvelteKitのブロックについてまとめました。

  • If
  • Else
  • Else if
  • Each
  • Key
  • Await

つかったもの

  • Vite + SvelteKit + Typescript
    • Flowbite-svelte
    • tailwind css

UIコンポーネントにはFlowbite-svelteを利用しました。
導入方法は前の記事で公開しています。

If

<script lang="ts">
  import { Button } from "flowbite-svelte";

  let bool = true;
</script>

{#if bool}
	<Button color="blue" on:click={() => bool = !bool}>
		TRUE
	</Button>
{/if}

{#if !bool}
	<Button color="green" on:click={() => bool = !bool}>
		FALSE
	</Button>
{/if}

if.gif

Else

<script lang="ts">
  import { Button } from "flowbite-svelte";

	let bool = true;
</script>

{#if bool}
	<Button color="blue" on:click={() => bool = !bool}>
		TRUE
	</Button>
{:else}
	<Button color="green" on:click={() => bool = !bool}>
		FALSE
	</Button>
{/if}

if.gif

Else if

<script lang="ts">
  import { Button } from "flowbite-svelte";

	let color = 'blue';
</script>

{#if color === 'blue'}
	<Button color="blue" on:click={() => color = 'green'}>
		Blue
	</Button>
{:else if color === 'green'}
	<Button color="green" on:click={() => color = 'red'}>
		Green
	</Button>
{:else}
	<Button color="red" on:click={() => color = 'blue'}>
		Red
	</Button>
{/if}

else if.gif

Each

<script lang="ts">
	let Array = [ '田中', '鈴木', '佐藤'];
</script>

{#each Array as	name, index }
	<p>
		{index}: {name}
	</p>
{/each}

indexを指定するときは↑のようにする

image.png

Key

{#key value}
    ・・・
{/key}

valueが変化すると中のブロックが再表示されます。
とある変化を拾い、再表示したいしたい時に使えそうです。

アニメーションで使ってみました。

<script lang="ts">
  import { Button, Select } from "flowbite-svelte";
  import { fly } from "svelte/transition";

  let duration = 200;

  let durations = [
    {value: 100, name: '早い'},
    {value: 500, name: '通常'},
    {value: 1000, name: '遅い'},
  ]
</script>

<div class="flex">
  {#key duration}
    <div class="w-1/5" in:fly={{ duration: duration, y: 200 }}>
      <Button color="light">
        登録
      </Button>
    </div>
  {/key}

  <Select class="w-4/5" items={durations} bind:value={duration} />
</div>  

key.gif

Await

普段Promiseを使っていると、ありがちなThenブロックが繋がりまくって可読性が低くなる現象をスッキリかけます
デモとして犬の画像をランダムに拾ってくるようにしました。

<script lang="ts">
  async function getDog() {
    const res = await fetch(`https://dog.ceo/api/breeds/image/random/1`);
    const text = await res.text();

    if (res.ok) {
      return JSON.parse(text).message[0]
    }
  }
</script>

{#await getDog()}
  <p>...waiting</p>
{:then url}
  <img src="{url}" width="200" alt="犬の画像">
{:catch error}
  <p style="color: red">{error.message}</p>
{/await}

かなりすっきりしますね!

dog.gif

2
1
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
2
1