Svelte 教學
Lily 嘅 Svelte 函式庫係標準實作:Svelte 5 runes、有型別嘅屬性、rest-prop 展開,同附有
bind:value.
你會建立啲乜
一個細細個嘅聯絡表單 — 有標籤嘅輸入欄、提交按鈕、雙向綁定、真實嘅鍵盤同螢幕閱讀器行為 — 先裸奔,再加樣式,大約 10 分鐘。
開始之前
你需要 git、Node 22 或以上,同 pnpm 10 或以上。任何 Svelte 5 項目都得 — 全新嘅 npx sv create 應用程式就夠。
步驟 1 — 攞到程式碼
git clone https://github.com/LilyDesignSystem/lily-design-system
cd lily-design-system/lily-design-system-svelte-headless
pnpm install
pnpm test # vitest — thousands of component cases
pnpm run storybook # browse all 571 components
元件放喺 src/lib/components/{Name}/,每個元件一個目錄,入面有 .svelte 檔案、佢嘅測試、stories 同文件並排放。將你需要嘅目錄複製入你嘅應用程式,或者依賴倉庫並直接匯入。
步驟 2 — 你第一個元件
<script>
import Button from "#lib/components/Button/Button.svelte";
function save() { console.log("saved"); }
</script>
<Button onclick={save}>Save</Button>
渲染成 <button class="button" type="button">。屬性有型別: type, disabled,
pressed (渲染 aria-pressed 用於切換按鈕), label (一個 aria-label 覆蓋),而任何額外屬性都會展開到根上。
步驟 3 — 組合一個細表單
<script>
import Form from "#lib/components/Form/Form.svelte";
import Field from "#lib/components/Field/Field.svelte";
import TextInput from "#lib/components/TextInput/TextInput.svelte";
import Button from "#lib/components/Button/Button.svelte";
let name = $state("");
</script>
<Form label="Contact form" onsubmit={handleSubmit}>
<Field label="Full name" required>
<TextInput id="name" label="Full name" bind:value={name} required />
</Field>
<Button type="submit">Save</Button>
</Form>
Field 將可見嘅 label 當作佢自己嘅屬性,而唔係嵌套嘅標籤元件 — 傳入一次,喺 Field,同 TextInput喺 label 提供無障礙名稱。 TextInput's value 係一個
$bindable rune 屬性,所以 bind:value 即刻畀你雙向綁定。
2026-08-29 已驗證: 呢個準確片段已經透過 svelte/server 編譯,並檢查過係單一、連結正確嘅 <label for> — 較早草稿嵌套咗獨立嘅 Label 入面嘅 Field,令佢渲染咗
兩個 標籤(其中一個係空嘅),因為 Field 已經由 label 屬性。
組合聯絡表單路由
係同一個模式,由真實嘅 e2e 同 axe 測試驗證過。
檢查你嘅成果: 運行應用程式,表單睇落好簡單 — 正如預期:樣式仲喺前面。按 Tab:焦點會移過每個控制項,標籤會被讀出,提交都運作。行為已經完成;外觀屬於你,而且係下一步。
步驟 4 — 加樣式
以上所有內容都渲染為純結構,準備好套用你嘅樣式。為類別掛鉤加樣式 —
.button, .text-input, .label,
.field — 喺你嘅全域樣式表,或者喺 app.html:
<link rel="stylesheet" href="/themes/dark.css" />
每個實例嘅調整透過 class 屬性進行,佢會附加到基礎掛鉤: <Button class="wide"> 渲染成
class="button wide".
步驟 5 — 睇晒佢運作
SvelteKit 範例應用程式 係同一個目錄,完全加咗樣式,附即時示範、Playwright e2e 測試同 axe-core 無障礙基線:
git clone https://github.com/LilyDesignSystem/lily-design-system
cd lily-design-system/lily-design-system-svelte-sveltekit-examples
pnpm install && pnpm run dev