1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【ひとりカレンダー】フロントエンド開発成長日記Advent Calendar 2022

Day 5

svelte/storeについてのまとめ - 後編

Last updated at Posted at 2022-12-05

はじめに

svelte/storeについてのまとめを作りたかった
今回はderivered custom bindingについて

使ったもの

  • Vite + Svelte + Typescript
  • skelton

前回(writable, Auto-subscribe, readable)

derivered

storeされている値が変化した時に一緒に変化させるメソッド。
computedみたいな感じ?
公式では時計と、所要時間という風に使ってました。

deliver.gif

// src/store.ts
import { readable, derived } from 'svelte/store';

export const count = readable(0, (set) => {
  let c = 1
  const interval = setInterval(() => {
    set(c);
    c++
  }, 1000);

  return function stop() {
    clearInterval(interval);
  };
});

export const double = derived(
  count,
  $count => $count * 2
)
<script lang="ts">
	import { count, double } from "../../store";
</script>

<div>現在: {$count}</div>
<div>2倍: {$double}</div>

custom

storeをカスタマイズすることができ、自前のメソッド等をstoreに持たせることができる。
storeの使い方が固定されている場合はカスタマイズした方が再利用性が高くなりそう。

custom.gif

// src/store.ts

import { writable } from 'svelte/store';

function createCount() {
  const { subscribe, set, update } = writable(0);

  return {
    subscribe,
    increment: () => update(n => n + 1),
    decrement: () => update(n => n - 1),
    reset: () => set(0)
  };
}

export const count = createCount();
// src/Home.svelte
<script>
  import { count } from "./store"
</script>

<div>
  The count is {$count}
</div>

<button class="btn btn-filled-surface" on:click={count.increment}>+</button>
<button class="btn btn-filled-surface" on:click={count.decrement}>-</button>
<button class="btn btn-filled-surface" on:click={count.reset}>reset</button>

binding

storeが書き込み可能な状態(subscribeや、Auto-subscribe)の時は、
他の変数と同じようにbindが使えます。
inputの要素を変えてみます。

binding.gif

// src/store.ts
import { writable } from 'svelte/store';

export const text = writable('');
// src/Home.svelte
<script>
  import { text } from './store';
</script>

<label for="text">
  <label for="text">
    <span>テキスト</span>
    <input type="text" id="text" bind:value={$text} minlength="2" required>
  </label>
</label>

<button class="btn btn-filled-surface" on:click={() => $text += 'こんにちは。'}>こんにちは。</button>
<button class="btn btn-filled-surface" on:click={() => $text = ''}>リセット</button>

<style>
  input {
    width: 245px;
  }
  button {
    margin-top: 10px;
  }
</style>

コードがかなり減りそうです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?