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

我们还可以将 bind:value<select> 元素一起使用:

¥We can also use bind:value with <select> elements:

App
<select
	bind:value={selected}
	onchange={() => answer = ''}
>

请注意,<option> 值是对象而不是字符串。Svelte 不介意。

¥Note that the <option> values are objects rather than strings. Svelte doesn’t mind.

由于我们没有设置 selected 的初始值,因此绑定将自动将其设置为默认值(列表中的第一个)。不过要小心 - 在初始化绑定之前,selected 仍未定义,因此我们不能盲目地在模板中引用 selected.id

¥[!NOTE] Because we haven’t set an initial value of selected, the binding will set it to the default value (the first in the list) automatically. Be careful though — until the binding is initialised, selected remains undefined, so we can’t blindly reference e.g. selected.id in the template.

上一页 下一页
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
<script>
	let questions = $state([
		{
			id: 1,
			text: `Where did you go to school?`
		},
		{
			id: 2,
			text: `What is your mother's name?`
		},
		{
			id: 3,
			text: `What is another personal fact that an attacker could easily find with Google?`
		}
	]);
 
	let selected = $state();
 
	let answer = $state('');
 
	function handleSubmit(e) {
		e.preventDefault();
 
		alert(
			`answered question ${selected.id} (${selected.text}) with "${answer}"`
		);
	}
</script>
 
<h2>Insecurity questions</h2>
 
<form onsubmit={handleSubmit}>
	<select
		value={selected}
		onchange={() => (answer = '')}
	>
		{#each questions as question}
			<option value={question}>
				{question.text}
			</option>
		{/each}
	</select>
 
	<input bind:value={answer} />
 
	<button disabled={!answer} type="submit">
		Submit
	</button>
</form>
 
<p>
	selected question {selected
		? selected.id
		: '[waiting...]'}
</p>