#Svelte https://svelte.jp/docs#component-format-script-4-prefix-stores-with-$-to-access-their-values `svelte/store`の関数を使ってStoreを作成できる。`writable`は読み書き可能なStore。 ```ts:stores.ts import { writable } from "svelte/store"; export const yourObj = writable<YourType>({}); ``` 呼び出しは`
をつけて呼ぶだけ。templateでもscriptでもOK。 ```html <div>{$yourObj.hoge}</div> <script lang="ts"> import { yourObj } from "~/stores"; $: hogehoge = $yourObj.hogehoge </script> ``` 更新は`set`を呼ぶだけ。 ```ts <script lang="ts"> import { yourObj } from "~/stores"; const handle = () => { yourObj.set(newObj) } </script> ``` 既存の値を参照して新しい値を入れる場合は`update`を使う。 ```ts <script lang="ts"> import { yourObj } from "~/stores"; const handle = () => { yourObj.update((current) => {...current, updatedObj}) } </script> ``` ## 具体例 ```html:App.svelte <script lang="ts"> import { humanStore } from "./store"; import { onMount } from "svelte"; let maxId = 1; onMount(() => humanStore.set({ "1": { id: "1", name: "Human1" } })); $: humanStoreStr = JSON.stringify($humanStore, null, 4); const handleClick = () => { const id = maxId + 1; humanStore.update((c) => ({ ...c, [id]: { id, name: `Human${id}` } })); maxId++; }; </script> <pre>{humanStoreStr}</pre> <button on:click={handleClick}>Add</button> ``` ```ts:store.ts import { writable } from "svelte/store"; export interface Human { id: string; name: string; } type HumanById = { [id: Human["id"]]: Human }; export const humanStore = writable<HumanById>({}); ``` ## MOC - 📚**ドキュメント** - 📖**ノウハウ** - [[SvelteのStoreでメソッドやgetterを定義]] - 💁**トラブルシューティング** - 🗃**用語定義**