Skip to main content

我们也可以在 select 元素上使用 bind:value

App.svelte
<select
	bind:value={selected}
	on:change={() => answer = ''}
>

注意 option 元素的值是对象,而不是字符串,不过 Svetle 并不在意。

因为我们没有给 selected 设置初始值,所以绑定会自动设置一个默认值,也就是列表的第一个值。但是要注意,在绑定初始化之前,selected 一直是未定义的,所以我们不能盲目地使用 selected.id 。(在最后的 p 元素中要加一个判断)

Next: 组输入

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
<script>
	let questions = [
		{
			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;
 
	let answer = '';
 
	function handleSubmit() {
		alert(
			`answered question ${selected.id} (${selected.text}) with "${answer}"`
		);
	}
</script>
 
<h2>Insecurity questions</h2>
 
<form on:submit|preventDefault={handleSubmit}>
	<select
		value={selected}
		on:change={() => (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>
initialising