Open8

svelte備忘録

りゅうのりゅうの

リアクティブステートメント

let count = 0;
$: doubled = count * 2;
りゅうのりゅうの

htmlタグ

<script>
	let string = `this string contains some <strong>HTML!!!</strong>`;
</script>

<p>{@html string}</p>
りゅうのりゅうの

Svelte のリアクティビティは代入によってトリガーされるため、push や splice のような配列のメソッドを使用しても更新が自動的に行われない。

これを修正する方法の1つとして、冗長に見えるかもしれませんが、代入を追加することです。

function addNumber() {
	numbers.push(numbers.length + 1);
	numbers = numbers;
}
りゅうのりゅうの

コンポーネントのprops

Nested.svelteのプロパティのデフォルト値を簡単に指定することができます。

<script>
	export let answer = 'a mystery';
</script>
App.svelte
<Nested answer={42}/>
<Nested />
りゅうのりゅうの

if

{#if count > 10}
	<p>{count} is greater than 10</p>
{:else if count < 5}
	<p>{count} is less than 5</p>
{:else}
	<p>{count} is between 5 and 10</p>
{/if}

each

	{#each colors as color}
		<button
			aria-current={selected === 'red'}
			aria-label="red"
			style="background: red"
			on:click={() => selected = 'red'}
		></button>
	{/each}
りゅうのりゅうの

コンポーネントでのイベント発信

App.svelte
<Inner on:message={handleMessage} />
Inner.svelte
<script>
	import { createEventDispatcher } from 'svelte';

	const dispatch = createEventDispatcher();

	function sayHello() {
		dispatch('message', {
			text: 'Hello!'
		});
	}
</script>
りゅうのりゅうの

input

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

<input bind:value={name} />

checkbox

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

<label>
	<input type="checkbox" bind:checked={yes} /></label>
りゅうのりゅうの

storeの値を呼び出し
store の名前の前に $ を付けることで、store の値を参照できます。