深入理解 Svelte Logic blocks
- 528字
- 3分鐘
- 2024-07-02
在 Svelte 中,Logic blocks是用於控制組件渲染的重要工具。本文將詳細介紹 Svelte 中的Logic blocks使用方法,包括條件渲染、循環渲染和模板插槽等,幫助開發者更高效地構建動態應用。
Logic blocks的類型
1. 條件渲染({#if ...}
)
條件渲染用於根據條件動態地渲染內容。Svelte 提供了 if
、else if
和 else
語法來實現條件渲染。
示例:
1<script>2 let loggedIn = false;3</script>4
5{#if loggedIn}6<p>Welcome back!</p>7{:else}8<p>Please log in.</p>9{/if}10
11<button on:click="{() => loggedIn = !loggedIn}">Toggle Login State</button>
2. 循環渲染({#each ...}
)
循環渲染用於遍歷數組或對象,並為每個元素生成對應的 HTML 結構。Svelte 提供了 each
語法來實現循環渲染。
示例:
1<script>2 let items = ["Apple", "Banana", "Cherry"];3</script>4
5<ul>6 {#each items as item, index}7 <li>{index + 1}: {item}</li>8 {/each}9</ul>10
11<button on:click="{() => items = [...items, 'New Item']}">Add Item</button>
3. 模板插槽(<slot>
)
模板插槽用於在組件中定義可插入的內容。Svelte 提供了 slot
語法來實現模板插槽。
示例:
1<script>2 import ChildComponent from "./ChildComponent.svelte";3</script>4
5<ChildComponent>6 <p>This is slot content from the parent component.</p>7</ChildComponent>8
9<!-- ChildComponent.svelte -->10<div>11 <h1>Child Component</h1>12 <slot></slot>13</div>
Logic blocks的高級用法
1. await
塊
await
塊用於處理異步操作的狀態,支持 then
和 catch
語法。
示例:
1<script>2 let promise = fetch("https://jsonplaceholder.typicode.com/posts").then(3 (response) => response.json(),4 );5</script>6
7{#await promise}8<p>Loading...</p>9{:then posts}10<ul>11 {#each posts as post}12 <li>{post.title}</li>13 {/each}14</ul>15{:catch error}16<p>Error: {error.message}</p>17{/await}
2. 動態組件(<svelte:component>
)
動態組件用於根據條件動態加載和渲染不同的組件。
示例:
1<script>2 import ComponentA from "./ComponentA.svelte";3 import ComponentB from "./ComponentB.svelte";4
5 let currentComponent = ComponentA;6</script>7
8<svelte:component this="{currentComponent}" />9
10<button11 on:click="{() => currentComponent = currentComponent === ComponentA ? ComponentB : ComponentA}"12>13 Toggle Component14</button>
3. key
塊
key
塊用於強制重新渲染特定部分的內容,通常用於處理複雜的動畫或狀態變化。
示例:
1<script>2 let count = 0;3</script>4
5{#key count}6<p>Keyed content: {count}</p>7{/key}8
9<button on:click="{() => count++}">Increment</button>
小結
Svelte 提供了一組強大的Logic blocks,用於控制組件的渲染行為。通過使用條件渲染、循環渲染、模板插槽、await
塊、動態組件和 key
塊,開發者可以更高效地構建動態應用,提升用戶體驗。