svelte 스터디#4 Logic

mhlee·2023년 2월 27일
0

svelte

목록 보기
5/6

if blocks

{#if 컨디션} 으로 시작하고,
{/if}로 닫는다. 닫을때는 "#"이 아니고 "/"이다.

<script>
	let user = { loggedIn: false };

	function toggle() {
		user.loggedIn = !user.loggedIn;
	}
</script>

{#if user.loggedIn}
<button on:click={toggle}>
	Log out
</button>
{/if}

{#if !user.loggedIn}
<button on:click={toggle}>
	Log in
</button>
{/if}

else blocks

{:else} 를 사용하여 else 블럭을 표현한다.

<script>
	let user = { loggedIn: false };

	function toggle() {
		user.loggedIn = !user.loggedIn;
	}
</script>

{#if user.loggedIn}
	<button on:click={toggle}>
		Log out
	</button>
{:else}
	<button on:click={toggle}>
		Log in
	</button>
{/if}

else-if blocks

{:else if 컨디션} 블럭을 사용하여 else-if 표현을 할수 있다.

<script>
	let x = 7;
</script>

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

each blocks

{#each 컬렉션 as 변수명} 으로 시작하고,
{/each}로 닫는다.
if 문과 규칙이 동일하다.

추가로 as 뒤에 변수를 하나 추가하여 index까지 fetch 가능하다.
아래 샘플에서 {#each cats as cat, idx} 부분이고, idx가 인덱스 값이다.

<script>
	let cats = [
		{ id: 'J---aiyznGQ', name: 'Keyboard Cat' },
		{ id: 'z_AbfPXTKms', name: 'Maru' },
		{ id: 'OUtn3pvWmpg', name: 'Henri The Existential Cat' }
	];
</script>

<h1>The Famous Cats of YouTube</h1>

<ul>
	{#each cats as cat, idx}
		<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}" rel="noreferrer">
			{idx +1}: {cat.name}
		</a></li>
	{/each}
</ul>

keyed each blocks

예제에서 첫번째 아이템 삭제 버튼을 누르면, 업데이트가 조금 이상하게 된다.
아이콘은 변하지 않고, Thing.svelte에서는 마지막 값이 삭제된것으로 인식된다.
설명이 정확히 이해되지는 않지만, 우선 키 포인트는 아래와 같다.

{#each things as thing (thing.id)}

정확한건 아니지만, 예제의 느낌상 text만 변경시 하위 컴포넌트인 Thing에서는 변경감지(?)가 애미해지는것 같다.
따라서 명확하게 each 구문에서 해당 아이템이 변경되었다는것을 인식시기키 위해 key 컬럼을 지정하는것 같다.
방식은 괄호와 key로 사용할 컬럼을 지정하는것 같다.

TODO : 이 파트는 사실 정확하게 이해가 되지 않는다. 추후 업데이트가 필요하다!!

App.svelte

<script>
	import Thing from './Thing.svelte';

	let things = [
		{ id: 1, name: 'apple' },
		{ id: 2, name: 'banana' },
		{ id: 3, name: 'carrot' },
		{ id: 4, name: 'doughnut' },
		{ id: 5, name: 'egg' },
	];

	function handleClick() {
		things = things.slice(1);
	}
</script>

<button on:click={handleClick}>
	Remove first thing
</button>

{#each things as thing (thing.id)}
	<Thing name={thing.name}/>
{/each}

Thing.svelte

<script>
	import { onDestroy } from 'svelte';

	const emojis = {
        apple: "🍎",
        banana: "🍌",
        carrot: "🥕",
        doughnut: "🍩",
        egg: "🥚"
	}

	// the name is updated whenever the prop value changes...
	export let name;

	// ...but the "emoji" variable is fixed upon initialisation of the component
	const emoji = emojis[name];

	// observe in the console which entry is removed
	onDestroy(() => {
		console.log('thing destroyed: ' + name)
	});
</script>

<p>
	<span>The emoji for { name } is { emoji }</span>
</p>

<style>
	p {
		margin: 0.8em 0;
	}
	span {
		display: inline-block;
		padding: 0.2em 1em 0.3em;
		text-align: center;
		border-radius: 0.2em;
		background-color: #FFDFD3;
	}
</style>

await blocks

프론트에서 비동기 처리는 필수이다.
await 상태에 대한 처리를 await 블럭을 이용해 직접 처리할수 있다.
아래 샘플은 getRandomNumber 메소드의 결과를 number라는 변수에 담고, 그 결과값을 출력하는 예제이다.

<script>
	async function getRandomNumber() {
		const res = await fetch(`/tutorial/random-number`);
		const text = await res.text();

		if (res.ok) {
			return text;
		} else {
			throw new Error(text);
		}
	}

	let promise = getRandomNumber();

	function handleClick() {
		promise = getRandomNumber();
	}
</script>

<button on:click={handleClick}>
	generate random number
</button>

<!-- replace this element -->
{#await promise}
  <p>...waiting</p>
{:then number}
  <p>The number is {number}</p>
{:catch error}
  <p style="color: red">{error.mesage}</p>
{/await}
profile
삽질하는 개발자

0개의 댓글