Bindings trong Svelte là cơ chế cho phép bạn kết nối trực tiếp giữa một biến trong một component và một giá trị hoặc một thuộc tính của một phần tử DOM. Điều này cho phép bạn tự động đồng bộ hóa dữ liệu giữa JavaScript và DOM mà không cần phải viết các hàm xử lý để cập nhật thủ công.

Text inputs

Bạn có thể sử dụng bindings để kết nối một biến trong component với một input element:

<script>
	let name = 'world';
</script>

<input bind:value={name} />

<h1>Hello {name}!</h1>
Svelte

Numeric inputs

Trong DOM, mọi thứ đều là một chuỗi. Điều đó không hữu ích khi bạn xử lý đầu vào số — type=”number” và type=”range” — vì điều đó có nghĩa là bạn phải nhớ ép buộc input.value trước khi sử dụng nó.

Với bind:value, Svelte sẽ giải quyết vấn đề đó cho bạn:

<script>
	let a = 1;
	let b = 2;
</script>

<label>
	<input type="number" bind:value={a} min="0" max="10" />
	<input type="range" bind:value={a} min="0" max="10" />
</label>

<label>
	<input type="number" bind:value={b} min="0" max="10" />
	<input type="range" bind:value={b} min="0" max="10" />
</label>

<p>{a} + {b} = {a + b}</p>
Svelte

Checkbox inputs

<script>
	let yes = false;
</script>

<label>
	<input type="checkbox" bind:checked={yes} />
	Yes! Send me regular email spam
</label>

{#if yes}
	<p>
		Thank you. We will bombard your inbox and sell
		your personal details.
	</p>
{:else}
	<p>
		You must opt in to continue. If you're not
		paying, you're the product.
	</p>
{/if}

<button disabled={!yes}>Subscribe</button>
Svelte

Select bindings

<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
		bind: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>
Svelte

Ở đây value của option có thể là object hoặc chuỗi đều được.

Group inputs

Nếu bạn có nhiều đầu vào type=”radio” hoặc type=”checkbox” liên quan đến cùng một giá trị, bạn có thể sử dụng bind:group cùng với thuộc tính value. Radio inputs trong cùng một group loại trừ lẫn nhau; checkbox inputs trong cùng một group tạo thành một mảng các giá trị được chọn.

<script>
	let scoops = 1;
	let flavours = [];

	const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
</script>

<h2>Size</h2>

{#each [1, 2, 3] as number}
	<label>
		<input
			type="radio"
			name="scoops"
			value={number}
			bind:group={scoops}
		/>

		{number} {number === 1 ? 'scoop' : 'scoops'}
	</label>
{/each}

<h2>Flavours</h2>

{#each ['cookies and cream', 'mint choc chip', 'raspberry ripple'] as flavour}
	<label>
		<input
			type="checkbox"
			name="flavours"
			value={flavour}
			bind:group={flavours}
		/>

		{flavour}
	</label>
{/each}

{#if flavours.length === 0}
	<p>Please select at least one flavour</p>
{:else if flavours.length > scoops}
	<p>Can't order more flavours than scoops!</p>
{:else}
	<p>
		You ordered {scoops} {scoops === 1 ? 'scoop' : 'scoops'}
		of {formatter.format(flavours)}
	</p>
{/if}
Svelte

Select multiple

Phần tử có thể có nhiều thuộc tính, trong trường hợp đó nó sẽ điền vào một mảng thay vì chọn một giá trị duy nhất.

<script>
	let scoops = 1;
	let flavours = [];

	const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
</script>

<h2>Size</h2>

{#each [1, 2, 3] as number}
	<label>
		<input
			type="radio"
			name="scoops"
			value={number}
			bind:group={scoops}
		/>

		{number} {number === 1 ? 'scoop' : 'scoops'}
	</label>
{/each}

<h2>Flavours</h2>

<select multiple bind:value={flavours}>
	{#each ['cookies and cream', 'mint choc chip', 'raspberry ripple'] as flavour}
		<option>{flavour}</option>
	{/each}
</select>

{#if flavours.length === 0}
	<p>Please select at least one flavour</p>
{:else if flavours.length > scoops}
	<p>Can't order more flavours than scoops!</p>
{:else}
	<p>
		You ordered {scoops} {scoops === 1 ? 'scoop' : 'scoops'}
		of {formatter.format(flavours)}
	</p>
{/if}
Svelte

Lưu ý rằng chúng ta có thể bỏ qua thuộc tính value trên , vì giá trị này giống với nội dung của phần tử.

Textarea inputs

<script>
	import { marked } from 'marked';
	let value = `Some words are *italic*, some are **bold**\n\n- lists\n- are\n- cool`;
</script>

<div class="grid">
	input
	<textarea bind:value></textarea>

	output
	<div>{@html marked(value)}</div>
</div>

<style>
	.grid {
		display: grid;
		grid-template-columns: 5em 1fr;
		grid-template-rows: 1fr 1fr;
		grid-gap: 1em;
		height: 100%;
	}

	textarea {
		flex: 1;
		resize: none;
	}
</style>
Svelte

Leave a Reply

Your email address will not be published. Required fields are marked *