Form値を変数にBind¶
"bind:value"にてformの入力値を変数にバインドできる。なお、バインドした値は通常、文字列としてバインドされるが、inputのtypeがnubmerかrangeの場合は数値としてバインドされる。また、チェックボックスの場合は"bind:checked"にてboolean型としてバインドできる。
app.svelte¶
<script>
import Bind from './Bind.svelte';
</script>
<main>
<Bind />
</main>
<style>
</style>
Bind.svelte¶
<script>
let name = '';
let val1 = 0;
let val2 = 0;
let yes = true;
</script>
<div>
<label>
<input placeholder="山田太郎" bind:value={name}>
</label>
<p>name: {name}</p>
<label>
<input type=number bind:value={val1} min=0 max=10>
<input type=range bind:value={val1} min=0 max=10>
</label>
<label>
<input type=number bind:value={val2} min=0 max=10>
<input type=range bind:value={val2} min=0 max=10>
</label>
<p>{val1} + {val2}: {val1 + val2}</p>
<label>
<input type=checkbox bind:checked={yes}>
</label>
<p>checked: {yes}</p>
</div>
<style>
label { display: flex;}
p { margin-top: 0.2em; margin-bottom: 0.5em}
</style>
適用イメージ