Svelte 教程
Lily 个 Svelte 组件库是规范实现:Svelte 5 runes、带类型个 props、剩余属性展开,以及用
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">。props 带有类型: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 作为自己个 prop,而不是嵌套一个标签组件——只需在 Field 上传入一次,TextInput 对应个 label 就会提供可访问名称。TextInput 个 value 是一个 $bindable rune prop,所以 bind:value 立刻就能给侬双向绑定。
2026-08-29 已验证:这段代码经 svelte/server 编译,并检查得到唯一且正确关联个 <label for>——早期草稿在 Field 里嵌套了单独个 Label,结果渲染出两个标签(其中一个为空),因为 Field 已经会根据 label prop 渲染自己个标签。
联系表单组合路由
采用同样个模式,并经过真实个端到端测试搭 axe 测试。
检查侬个成果:运行应用,表单看起来老朴素——这正是预期:样式还在后面。按下 Tab:焦点会依次经过每个控件,标签会被朗读,提交也能正常工作。行为已经完成;外观由侬决定,这就是下一步。
第 4 步——添加样式
以上所有内容渲染出来侪是纯结构,随时可以套用侬个样式。在全局样式表中为搿眼类名钩子设置样式——
.button、.text-input、.label、
.field——或者在 app.html 中链接一个现成个主题:
<link rel="stylesheet" href="/themes/dark.css" />
针对单个实例个微调通过 class prop 完成,伊会追加到基础钩子之后:<Button class="wide"> 渲染为
class="button wide"。
第 5 步——看看伊个完整效果
SvelteKit 示例应用是同一套目录个完整带样式版本,带有现场演示、Playwright 端到端测试搭 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