Skip to main content
Svelte 基础
介绍
响应式
属性
逻辑
事件
绑定
类和样式
Actions
过渡动画
Svelte 进阶
高级响应性
复用内容
Motion
高级绑定
高级过渡效果
Context API
特殊元素
<script module>
后续步骤
SvelteKit 基础
介绍
路由
加载数据
请求头和 Cookie
共享模块
表单
API 路由
$app/state
错误和重定向
SvelteKit 进阶
钩子函数
页面选项
链接选项
高级路由
高级加载
环境变量
结论

当你需要验证数据时,类特别有用。在这个 Box 类的例子中,不应该在超过滑块允许的最大值的时候继续扩大,但这正是现在发生的情况。

我们可以通过将 widthheight 替换为 getterssetters(也称为 accessors)来解决这个问题。首先,将它们转换为私有属性

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

	constructor(width, height) {
		this.#width = width;
		this.#height = height;
	}

	// ...
}

然后,创建一些 getters 和 setters:

App
class Box {
	// ...

	get width() {
		return this.#width;
	}

	get height() {
		return this.#height;
	}

	set width(value) {
		this.#width = value;
	}

	set height(value) {
		this.#height = value;
	}

	embiggen(amount) {
		this.width += amount;
		this.height += amount;
	}
}

最后,在 setters 中添加验证:

App
set width(value) {
	this.#width = Math.max(0, Math.min(MAX_SIZE, value));
}

set height(value) {
	this.#height = Math.max(0, Math.min(MAX_SIZE, value));
}

现在无论是通过范围输入的 bind:value,还是通过 embiggen 方法,无论你多用力地按按钮,都不可能将盒子尺寸增加到超过安全限制。

在 GitHub 编辑此页面

<script>
const MAX_SIZE = 200;

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

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>

loading Svelte compiler...
loading svelte compiler