Logic
HTML에는 조건문 및 루프와 같은 논리를 표현하는 방법이 없다. 마크업을 조건부로 랜더링 하기 위해 IF블럭으로 감싼다.
<script>
let user = { loggedIn: false }; // 질문) false?! 음.. 무슨 말일까..? -> 기본값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블록을 사용할 수 있다.
<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}
<!--위의 코드를 아래와 같이 좀 더 간단하게 만들 수 있음-->
<script>
let user = { loggedIn: false };
function toggle() {
user.loggedIn = !user.loggedIn;
}
</script>
<button on:click={toggle}>{user.loggedIn ? `Log out` : `Log In`}</button>
여러 조건일 경우 else if와 함께 연결할 수 있다.
<script>
let x = 7;
</script>
{#if x > 10}
<p>{x} is greater than 10</p>
{:else if 5 > x}
<p>{x} is less than 5</p>
{:else}
<p>{x} is between 5 and 10</p>
{/if}
데이터 목록을 반복해야하는 경우 each블록을 사용한다. 두번째 인수로 현재 인덱스를 가져올 수 있다.
const arr = [1, 4, 9, 16];
arr.map(x => x * 2) // [2, 8, 18, 32]
arr.map((x, i) => x * i) // i가 인덱스, 즉 x 값의 위치가 넘어옴
/*
* 1st --> x = 1, i = 0
* 2nd --> x = 4, i = 1
* 3rd --> x = 9, i = 2
* 4th --> x = 16, i = 3
*/
<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 { id, name }, i}
<!-- 여기서 id, name이 한 셋/ i가 두번째 인수로 인덱스 출력 -->
<li><a target="_blank" href="https://www.youtube.com/watch?v={id}" rel="noreferrer">
{i + 1}: {name}
</a></li>
{/each}
</ul>
대부분의 애플리케이션은 비동기 데이터를 처리해야한다. await블록을 사용하면 마크업에서 직접 값을 기다릴 수 있다.
<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>
{#await promise}
<p>...waiting</p>
{:then number}
<p>The number is {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}