스벨트에서 사용하는 간단한 속성들과 로직 블럭들에 대해 알아보도록 하겠습니다.
<img src={src} alt="A man dances.">
=> <img {src} alt="A man dances.">
{@html…}
일반적으로 문자열은 일반 텍스트로 삽입됩니다 그러나 HTML을 구성 요소에 직접 렌더링 할 경우 {@html…}
태그를 사용합니다
<script>
let string = `this string contains some <strong>HTML!!!</strong>`;
</script>
<p>{@html string}</p>
<script>
let count = 0;
function incrementCount() {
count += 1;
}
</script>
<button on:click={incrementCount}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
<script>
let count = 0;
$: doubled = count * 2;
//참조된 값이 변경 될 때 마다 다시 실행
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Clicked {count} {count === 1 ? 'time' : 'times'}
</button>
<p>{count} doubled is {doubled}</p>
선언한 값 앞에 $:
을 사용하게 되면, 참조된 값이 변경될 때 마다 다시 실행하게 됩니다. 그렇기 때문에 값을 탐지하고 있다가 데이터가 변화되는 상황이 생기면 특정 기능이 수행됩니다.
반응성 구문인 $:
은 반응성을 계측하는 것일 뿐, 즉각 반영은 아닙니다.
조금의 시간 차이가 있어서 연속적인 작업이 있을 때 오류가 생길 수 있습니다. 따라서, svelte의 lifecycle중 하나인 tick
을 이용해서 반응성 반영을 보장받을 수 있도록 함께 사용합니다.
ex)
let name = '';
let age = '';
$: pow = age * age;
//age값이 변할때마다 pow값을 age*age로 저장
const console3 = () => {
console.log(`3 → name: ${name}, age: ${age}, pow: ${pow}`);
}
$: age, (() => { console.log(`0 → age`); }
// age가 변경될 때 마다 출력
)()
$: [age, name], (() => { console.log(`1 → age, name`); }
//age, name이 변경될 때 마다 출력
)()
$: name, (() => { console.log(`2 → name: ${name}, age: ${age}, pow: ${pow}`); }
// name, age가 변경될 때 마다 출력
)()
$: { console3(); }
// 렌더링 될 때만 출력
$: (() => { console.log(`4 → name: ${name}, age: ${age}, pow: ${pow}`); })()
// name, age가 변경될 때 마다 출력
$: if(age >= 1) { console.log(`5 → name: ${name}, age: ${age}, pow: ${pow}`); }
// age가 1이상이고 name, age가 변경될 때 마다 출력
<main>
<input type="text" bind:value={name} placeholder="name" />
<input type="number" bind:value={age} placeholder="age" />
</main>
<style> input { border: 1px solid orange; } </style>
import Nested from './Nested.svelte';
<Nested answer={42}/>
<Nested/>
export let answer = 'a mystery';
<p>The answer is {answer}</p>
export와 import를 통해서 다른 파일에서 값을 props로 넘겨 사용할 수 있습니다.
svelte에서는 block
들을 사용하여 if, else, await 등을 사용합니다.
구문을 시작할 때는 {#..}
을 사용하며 반드시 {/..}
를 사용하여 닫아주어야 합니다.
If
block{#if user.loggedIn}
<button on:click={toggle}>
Log out
</button>
{/if}
{#if !user.loggedIn}
<button on:click={toggle}>
Log in
</button>
{/if}
Else
block{#if user.loggedIn}
<button on:click={toggle}>
Log out
</button>
{:else}
<button on:click={toggle}>
Log in
</button>
{/if}
Else-if
block{#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
block<ul>
{#each cats as cat}
<li><a target="_blank" href="https://www.youtube.com/watch?v={cat.id}" rel="noreferrer">
{cat.name}
</a></li>
{/each}
</ul>
Keyed each
block{#each things as thing (thing.id)}
<Thing name={thing.name}/>
{/each}
Await
block{#await promise}
<p>...waiting</p>
{:then number}
<p>The number is {number}</p>
{:catch error}
<p style="color: red">{error.message}</p>
{/await}
async await 사용
let planetPromise = getPlanet();
async function getPlanet() {
const id = Math.floor(Math.random() * 60) + 1;
const response = await fetch(`https://swapi.co/api/planets/${id}`);
const data = await response.json();
return data.name;
}
<p>
{#await planetPromise}
Loading planet...
{:then planet}
Your next planet is {planet}.
{:catch someError}
System error: {someError.message}.
{/await}
</p>
<button on:click={() => planetPromise = getPlanet()}>
Explore the next planet
</button>