Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

不仅仅是变量可以具有响应性 - 在 Svelte 中,我们还可以使类的属性具有响应性。

¥It’s not just variables that can be made reactive — in Svelte, we can also make properties of classes reactive.

让我们将 Box 类的 widthheight 属性变为响应式:

¥Let’s make the width and height properties of our Box class reactive:

App
class Box {
	width = $state(0);
	height = $state(0);
	area = 0;

	// ...
}

现在,当我们与范围输入交互或单击 ‘embiggen’ 按钮时,框会做出反应。

¥Now, when we interact with the range inputs or click the ‘embiggen’ button, the box reacts.

我们还可以使用 $derived,以便 box.area 被动更新:

¥We can also use $derived, so that box.area updates reactively:

App
class Box {
	width = $state(0);
	height = $state(0);
	area = $derived(this.width * this.height);

	// ...
}

除了 $state$derived,你还可以使用 $state.raw$derived.by 来定义反应字段。

¥[!NOTE] In addition to $state and $derived, you can use $state.raw and $derived.by to define reactive fields.

上一页 下一页
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<script>
	const MAX_SIZE = 200;
 
	class Box {
		width = 0;
		height = 0;
		area = 0;
 
		constructor(width, height) {
			this.width = width;
			this.height = height;
		}
 
		embiggen(amount) {
			this.width += amount;
			this.height += amount;
		}
	}
 
	const box = new Box(100, 100);
</script>
 
<label>
	<input type="range" bind:value={box.width} min={0} max={MAX_SIZE} />
	{box.width}
</label>
 
<label>
	<input type="range" bind:value={box.height} min={0} max={MAX_SIZE} />
	{box.height}
</label>
 
<button onclick={() => box.embiggen(10)}>embiggen</button>
 
<hr>
 
<div
	class="box"
	style:width="{box.width}px"
	style:height="{box.height}px"
>
	{box.area}
</div>
 
<style>
	label {
		display: flex;
		align-items: center;
	}
 
	hr {
		margin: 1em 0;
		border: none;
		border-bottom: 1px solid #888;
	}
 
	.box {
		background: radial-gradient(at 25% 25%, hsl(15 100 60), hsl(15 100 50)) ;
		border-radius: 2px;
		filter: drop-shadow(0 0 10px hsl(15 100 50 / 0.3));
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}
</style>