Skip to main content

$bindable

通常,props 是单向的,从父级到子级。这使得你很容易理解数据在你的应用中是如何流动的。

¥Ordinarily, props go one way, from parent to child. This makes it easy to understand how data flows around your app.

在 Svelte 中,组件 props 可以绑定,这意味着数据也可以从子级流到父级。这不是你应该经常做的事情,但如果谨慎使用,它可以简化你的代码。

¥In Svelte, component props can be bound, which means that data can also flow up from child to parent. This isn’t something you should do often, but it can simplify your code if used sparingly and carefully.

它还意味着可以在子元素中改变状态代理。

¥It also means that a state proxy can be mutated in the child.

正常 props 也可以进行修改,但强烈不建议这样做 — 如果 Svelte 检测到组件正在修改状态,它会警告你,而不是 ‘own’。

¥[!NOTE] Mutation is also possible with normal props, but is strongly discouraged — Svelte will warn you if it detects that a component is mutating state it does not ‘own’.

要将 prop 标记为可绑定,我们使用 $bindable 符文:

¥To mark a prop as bindable, we use the $bindable rune:

FancyInput
<script>
	let { value = $bindable(), ...props } = $props();
</script>

<input bind:value={value} {...props} />

<style>
	input {
		font-family: 'Comic Sans MS';
		color: deeppink;
	}
</style>
<script lang="ts">
	let { value = $bindable(), ...props } = $props();
</script>

<input bind:value={value} {...props} />

<style>
	input {
		font-family: 'Comic Sans MS';
		color: deeppink;
	}
</style>

现在,使用 <FancyInput> 的组件可以添加 bind: 指令(demo):

¥Now, a component that uses <FancyInput> can add the bind: directive (demo):

/// App.svelte
<script>
	import FancyInput from './FancyInput.svelte';

	let message = $state('hello');
</script>

<FancyInput bind:value={message} />
<p>{message}</p>

父组件不必使用 bind: — 它只需传递普通 prop。有些父级不想听子级说些什么。

¥The parent component doesn’t have to use bind: — it can just pass a normal prop. Some parents don’t want to listen to what their children have to say.

在这种情况下,你可以为根本没有传递任何 prop 的情况指定一个后备值:

¥In this case, you can specify a fallback value for when no prop is passed at all:

FancyInput
let { let value: anyvalue = function $bindable<"fallback">(fallback?: "fallback" | undefined): "fallback"

Declares a prop as bindable, meaning the parent component can use bind:propName={value} to bind to it.

let { propName = $bindable() }: { propName: boolean } = $props();

https://svelte.dev/docs/svelte/$bindable

$bindable
('fallback'), ...let props: anyprops } = function $props(): any

Declares the props that a component accepts. Example:

let { optionalProp = 42, requiredProp, bindableProp = $bindable() }: { optionalProp?: number; requiredProps: string; bindableProp: boolean } = $props();

https://svelte.dev/docs/svelte/$props

$props
();
上一页 下一页