Showing data is only step one—you also need to capture input reliably. The bind: directive is a double-ended link you'll use constantly in student projects.
Key terms
bind:: A Svelte directive that keeps an input and a variable in sync so a change on either side updates the other immediately.- Two-way binding: A structure where input values and state mirror each other, removing the need for separate handlers.
- Form state object: A single object that groups multiple inputs for easier saving and validation.
- localStorage: A browser key-value store that persists strings even after a refresh.
Core ideas
Two-way binding lets inputs and state update simultaneously, making saving painless. Organizing the values into one form object gives you a single source of truth for submission and validation. LocalStorage is a lightweight browser store; writing the bound state to it restores the data after refreshes.
Code example
We'll build a small club application form that auto-saves.
<script>
let form = JSON.parse(localStorage.getItem('application') ?? '{}');
$: localStorage.setItem('application', JSON.stringify(form));
</script>
<input bind:value={form.teamName} placeholder="Team name" />
<textarea bind:value={form.goal} placeholder="Problem you want to solve" />
<label>
<input type="checkbox" bind:checked={form.ready} /> Presentation ready
</label>
Every bind:value and bind:checked mutates the appropriate field inside form. The reactive $: statement runs whenever form changes, writing fresh data to LocalStorage. Open the page in the same browser later and your answers remain.
Why it matters
Applications, surveys, and club checklists are all forms. Using bind: keeps the input flow consistent so you don't need an event handler for every field. Managing one object ensures the submit function sees the latest data in one shot. The habit also prepares you to connect stores and server actions later in the series.
Practice
- Follow along: reproduce the example and ensure inputs survive a refresh.
- Extend: add a select or radio group to expand the form object.
- Debug: if a value doesn't update, confirm
bind:targets the right property (value,checked,group, etc.). - Done when: editing the form changes both the UI and LocalStorage immediately.
Wrap-up
Once two-way binding feels natural, building and validating forms becomes faster. Up next, we'll let multiple components share the same state via stores.
💬 댓글
이 글에 대한 의견을 남겨주세요