使用 npm 安装 Svelte:
npx degit sveltejs/template my-svelte-app
cd my-svelte-app
npm install
npm run dev
创建一个简单的 Svelte 组件
<!-- App.svelte -->
<script>
let name = 'world';
</script>
<main>
<h1>Hello {name}!</h1>
<input bind:value={name} placeholder="Enter your name">
</main>
<style>
main {
text-align: center;
padding: 1em;
}
h1 {
color: #ff3e00;
}
</style>
响应式设计
<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
组件通信
<!-- Child.svelte -->
<script>
export let count;
</script>
<p>Count is {count}</p>
<!-- App.svelte -->
<script>
import Child from './Child.svelte';
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>
Increment
</button>
<Child {count} />
组件语法:Svelte 组件使用 .svelte 文件扩展名,包含 <script>
, <style>
, 和 HTML 模板。
<script>
let name = 'world';
</script>
<main>
<h1>Hello {name}!</h1>
</main>
<style>
h1 {
color: red;
}
</style>
绑定属性:使用 bind:
语法将输入元素的值绑定到组件状态。
<input bind:value={name}>
事件处理:使用 on:
语法添加事件监听器。
<button on:click={increment}>Increment</button>
条件渲染:使用 {#if}
语法进行条件渲染。
{#if count > 0}
<p>Count is {count}</p>
{/if}
循环渲染:使用 {#each}
语法进行列表渲染。
{#each items as item}
<p>{item}</p>
{/each}
props 传递:通过 export let
语法定义组件的属性。
<script>
export let name;
</script>
<p>Hello {name}!</p>
Store(状态管理)
使用 Svelte 的 writable
store 管理全局状态:
// store.js
import { writable } from 'svelte/store';
export const count = writable(0);
<!-- App.svelte -->
<script>
import { count } from './store.js';
</script>
<button on:click={() => $count += 1}>
Increment
</button>
<p>Count is {$count}</p>
动画和过渡
使用 Svelte 的内置动画和过渡功能创建动态效果:
<script>
import { fly } from 'svelte/transition';
let visible = true;
</script>
<button on:click={() => visible = !visible}>
Toggle
</button>
{#if visible}
<p transition:fly={{ y: 200, duration: 500 }}>
Fly in and out
</p>
{/if}
服务端渲染(SSR)
使用 SvelteKit 实现服务端渲染:
npm init svelte@next my-sveltekit-app
cd my-sveltekit-app
npm install
npm run dev
Svelte 通过其独特的编译时框架理念和简洁的语法,提供了一种高效、灵活且易于使用的前端开发方式。其性能优势和开发体验使其成为构建现代 Web 应用的强大工具。