响应式
声明状态
更新状态
模板语法
样式
<h1 class="title">我是红色的</h1>
<button style="font-size: 10rem;">我是一个按钮</button>
<style>
.title {
color: red;
}
</style>
DOM循环
点击事件
DOM引用
条件渲染
<script>
const TRAFFIC_LIGHTS = ["红灯", "黄灯", "绿灯"];
let lightIndex = $state(0);
const light = $derived(TRAFFIC_LIGHTS[lightIndex]);
function nextLight() {
lightIndex = (lightIndex + 1) % TRAFFIC_LIGHTS.length;
}
</script>
<button onclick={nextLight}>下一个灯</button>
<p>现在亮着的是: {light}</p>
<p>
你应该
{#if light === "红灯"}
<span>停下</span>
{:else if light === "黄灯"}
<span>慢行</span>
{:else if light === "绿灯"}
<span>赶紧走</span>
{/if}
</p>
static const TRAFFIC_LIGHTS = ["红灯", "黄灯", "绿灯"];
<let/lightIndex=0>
<const/light=TRAFFIC_LIGHTS[lightIndex]>
<button onClick() { lightIndex = (lightIndex + 1) % TRAFFIC_LIGHTS.length }>
下一个灯
</button>
<p>现在亮着的是: ${light}</p>
<p>
你应该
<if=light === "红灯">停下</if>
<else if=light === "黄灯">慢行</else>
<else>赶紧走</else>
</p>
生命周期
组件加载时
组件卸载时
<script>
let time = $state(new Date().toLocaleTimeString());
$effect(() => {
const timer = setInterval(() => {
time = new Date().toLocaleTimeString();
}, 1000);
return () => clearInterval(timer);
});
</script>
<p>当前时间: {time}</p>
组件组合
组件Props传参
向父组件emit事件
<script>
import AnswerButton from "./AnswerButton.svelte";
let isHappy = $state(true);
function onAnswerNo() {
isHappy = false;
}
function onAnswerYes() {
isHappy = true;
}
</script>
<p>你快乐吗?</p>
<AnswerButton onYes={onAnswerYes} onNo={onAnswerNo} />
<p style="font-size: 50px;">{isHappy ? "😀" : "😥"}</p>
slot插槽
slot插槽内容
上下文
<script>
import { setContext } from "svelte";
import UserProfile from "./UserProfile.svelte";
import createUserState from "./createUserState.svelte.js";
const user = createUserState({
id: 1,
username: "abcdefg",
email: "[email protected]",
});
setContext("user", user);
</script>
<h1>欢迎回来, {user.username}</h1>
<UserProfile />
<let/user={
id: 1,
username: "abcdefg",
email: "[email protected]",
}>
<const/updateUsername(newUsername) {
user = { ...user, username: newUsername };
}>
<h1>欢迎回来, ${user.username}</h1>
<context={ ...user, updateUsername }>
<UserProfile />
</context>
表单输入
输入框
复选框
单选框
<script>
let picked = $state("red");
</script>
<div>你选择了: {picked}</div>
<input id="blue-pill" bind:group={picked} type="radio" value="blue" />
<label for="blue-pill">蓝色</label>
<input id="red-pill" bind:group={picked} type="radio" value="red" />
<label for="red-pill">红色</label>
选择器
<script>
let selectedColorId = $state(2);
const colors = [
{ id: 1, text: "红" },
{ id: 2, text: "蓝" },
{ id: 3, text: "绿" },
{ id: 4, text: "灰", isDisabled: true },
];
</script>
<select bind:value={selectedColorId}>
{#each colors as color}
<option value={color.id} disabled={color.isDisabled}>
{color.text}
</option>
{/each}
</select>
static const colors = [
{ id: 1, text: "红" },
{ id: 2, text: "蓝" },
{ id: 3, text: "绿" },
{ id: 4, text: "灰", isDisabled: true },
];
<let/selectedColorId=2>
<select value:=selectedColorId>
<for|{ id, isDisabled, text }| of=colors>
<option value=id disabled=isDisabled>
${text}
</option>
</for>
</select>
Web应用特性
渲染应用
fetch获取数据
<script>
import useFetchUsers from "./useFetchUsers.svelte.js";
const response = useFetchUsers();
</script>
{#if response.isLoading}
<p>正在获取用户信息……</p>
{:else if response.error}
<p>获取用户信息出错</p>
{:else if response.users}
<ul>
{#each response.users as user}
<li>
<img src={user.picture.thumbnail} alt="user" />
<p>
{user.name.first}
{user.name.last}
</p>
</li>
{/each}
</ul>
{/if}
<try>
<await|{ results: users }|=fetch("https://randomuser.me/api/?results=3").then(res => res.json())>
<ul>
<for|{ picture, name }| of=users>
<li>
<img src=picture.thumbnail alt="user">
<p>${name.first} ${name.last}</p>
</li>
</for>
</ul>
</await>
<@placeholder>
<p>正在获取用户信息……</p>
</@placeholder>
<@catch|error|>
<p>获取用户信息出错</p>
</@catch>
</try>