一般来说,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:
<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
.
<script>
let name = $state('world');
</script>
<input value={name} />
<h1>Hello {name}!</h1>