Logic / Keyed each blocks a. Basics b. Adding data c. Dynamic attributes d. Styling e. Nested components f. Making an app a. Assignments b. Declarations c. Statements d. Updating arrays and objects a. Declaring props b. Default values c. Spread props a. If blocks b. Else blocks c. Else-if blocks d. Each blocks e. Keyed each blocks f. Await blocks a. DOM events b. Inline handlers c. Event modifiers d. Component events e. Event forwarding f. DOM event forwarding a. undefined b. Numeric inputs c. Checkbox inputs d. Group inputs e. Textarea inputs f. Select bindings g. Select multiple h. Contenteditable bindings i. Each block bindings j. Media elements k. Dimensions l. This m. Component bindings n. Binding to component instances a. onMount b. onDestroy c. beforeUpdate and afterUpdate d. tick a. Writable stores b. Auto-subscriptions c. Readable stores d. Derived stores e. Custom stores f. Store bindings a. Tweened b. Spring a. The transition directive b. Adding parameters c. In and out d. Custom CSS transitions e. Custom JS transitions f. Transition events g. Global transitions h. Deferred transitions i. Key blocks a. The animate directive a. The use directive b. Adding parameters a. The class directive b. Shorthand class directive c. Inline styles d. The style directive a. Slots b. Slot fallbacks c. Named slots d. Checking for slot content e. Slot props a. setContext and getContext a. <svelte:self> b. <svelte:component> c. <svelte:element> d. <svelte:window> e. <svelte:window> bindings f. <svelte:document> g. <svelte:body> h. <svelte:head> i. <svelte:options> j. <svelte:fragment> a. Sharing code b. Exports a. The @debug tag b. HTML tags a. Congratulations!
デフォルトでは、each
ブロックの値を変更すると、ブロックの 末尾 にアイテムを追加・削除し、変更された値を更新します。これはあなたが望むものではないかもしれません。
説明するより見ていただいたほうがわかりやすいしょう。まず Console
をクリックしてコンソールを開き、それから 'Remove first thing' ボタンを何度かクリックして、何が起きるか確認してください。先頭の <Thing>
コンポーネントは削除されず、末尾の DOM ノードが削除されます。そして残りの DOM ノードの name
の値は更新されますが、絵文字は更新されません。
代わりに、先頭の <Thing>
コンポーネントとその DOM ノードだけを削除して、残りには影響を与えないようにしたいと思います。
そのためには、each
ブロックに一意な識別子 (または"key") を指定します。
{# each things as thing ( thing .id)}
< Thing name = { thing .name} />
{/ each }
ここで、(thing.id)
は key であり、コンポーネントが更新されたときに変更するDOMノードを特定する方法を Svelte に伝えます。
Svelte は内部的に Map
を使用しているので、どんなオブジェクトでもキーとして使用できます。つまり (thing.id)
の代わりに (thing)
を使うことができます。しかし、文字列または数値を使用する方が一般的に安全です。なぜなら、例えばAPIサーバーからの新しいデータで更新する場合に、参照が等しくなくても同一性が持続することを意味するからです。
Show me