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

一般来说,Svelte 中的数据流是自上而下的 - 父组件可以在子组件上设置 props,组件可以在元素上设置属性,但不能反过来。

¥As a general rule, data flow in Svelte is top down — a parent component can set props on a child component, and a component can set attributes on an element, but not the other way around.

有时打破该规则很有用。以此组件中的 <input> 元素为例 — 我们可以添加一个 oninput 事件处理程序,将 name 的值设置为 event.target.value,但有点...样板。正如我们将看到的,其他表单元素的情况会变得更糟。

¥Sometimes it’s useful to break that rule. Take the case of the <input> element in this component — we could add an oninput event handler that sets the value of name to event.target.value, but it’s a bit... boilerplatey. It gets even worse with other form elements, as we’ll see.

相反,我们可以使用 bind:value 指令:

¥Instead, we can use the bind:value directive:

App
<input bind:value={name}>

这意味着,不仅对 name 值的更改会更新输入值,而且对输入值的更改也会更新 name

¥This means that not only will changes to the value of name update the input value, but changes to the input value will update name.

上一页 下一页
1
2
3
4
5
6
7
8
<script>
	let name = $state('world');
</script>
 
<input value={name} />
 
<h1>Hello {name}!</h1>