Svelte 입문 (Props, Logic)

Shy·2024년 9월 23일

Svelte

목록 보기
2/12

Props

props는 property의 약자이고, 상위 컴포넌트가 하위 컴포넌트에 값을 전달할 때 사용하는 속성이다.

Declaring props

리액트에서 했던, 값을 받아서 그것을 상속해서 넣어서 출력하는 느낌이다.

<!-- App.svelte -->
<script>
	import Nested from './Nested.svelte';
</script>

<Nested answer={42} />
<Nested />
<!-- Nested.svelte -->
<script>
	export let answer;
</script>

<p>The answer is {answer}</p>
The answer is 42

The answer is undefined

Default values

export default를 생각하면 편할듯.
만약에 값이 전달되지 않으면, default값을 출력한다.

<!-- App.svelte -->
<script>
	import Nested from './Nested.svelte';
</script>

<Nested answer={42} />
<Nested />
<!-- Nested.svelte -->
<script>
	export let answer = 'a mystery';
</script>

<p>The answer is {answer}</p>
The answer is 42

The answer is a mystery

Spread props

스프레드 연산자를 사용하여 props에 값을 전달한다.

<!-- App.svelte -->
<script>
	import Info from './Info.svelte';

	const pkg = {
		name: 'svelte',
		version: 3,
		speed: 'blazing',
		website: 'https://svelte.dev'
	};
</script>

<Info {...pkg} />
<!-- Info.svelte -->
<script>
	export let name;
	export let version;
	export let speed;
	export let website;
</script>

<p>
	The <code>{name}</code> package is {speed} fast. Download version {version} from
	<a href="https://www.npmjs.com/package/{name}">npm</a>
	and <a href={website}>learn more here</a>
</p>
The svelte package is blazing fast. Download version 3 from npm and learn more here

npm과 learn more here에 href가 있어서 파란색 링크로 나타난다.

Logic

If blocks

<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}

클릭할때마다 Log in, Log out버튼이 번갈아가면서 나타남!!

약간 react의 useEffect와 비슷한 느낌같다.
이걸 좀 더 간단하게 개량한다면 아래와 같이 만들 수 있다.

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

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

<button on:click={toggle}> 
	{user.loggedIn ? 'Log in' : 'Log out'}
</button>

Else blocks

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

<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 blocks

  • for each
    • 향상된 for문
    • 배열이나 컬렉션의 모든 요소를 순회하는 데 사용되는 문법이다.
<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}
		<li>
			<a target="_blank" rel="noreferrer" href="https://www.youtube.com/watch?v={id}">
				{i + 1}: {name}
			</a>
		</li>
	{/each}
</ul>

생성자 함수를 활용하면 아래와 같이 생성하는것도 가능하다!

<script>
	function Cat(id, name) {
		this.id = id;
		this.name = name;
	}
	let cats = [
		new Cat('J---aiyznGQ', 'Keyboard Cat'),
		new Cat('z_AbfPXTKms', 'Maru'),
		new Cat('OUtn3pvWmpg', 'Henri The Existential Cat')
	];
</script>

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

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

Keyed each blocks

해설

왜 key를 쓰면, 제대로 제거가 되는데 안쓰면 이상하게 제거가 되는거지...?

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

	let things = [
		{ id: 1, color: 'darkblue' }, // 파랑
		{ id: 2, color: 'indigo' }, // 보라
		{ id: 3, color: 'deeppink' }, // 핑크
		{ id: 4, color: 'salmon' }, // 주황
		{ id: 5, color: 'gold' } //노랑
	];

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

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

<div style="display: grid; grid-template-columns: 1fr 1fr; grid-gap: 1em">
	<div>
		<h2>Keyed</h2>
		{#each things as thing (thing.id)}
			<Thing current={thing.color} />
		{/each}
	</div>

	<div>
		<h2>Unkeyed</h2>
		{#each things as thing}
			<Thing current={thing.color} />
		{/each}
	</div>
</div>

Await blocks

<script>
	let promise = getRandomNumber();

	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);
		}
	}

	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}

아래는 기본 await then catch 문법이다.
then으로 결과에 따라 실행을 하고, catch로 에러를 받는다.

const sampleFunc = () => {
    asyncFunc() // asyncFunc 함수는 Promise 객체를 반환한다
        .then(result => console.log(result))
		.catch(err => console.log(err))

// 이런 식으로도 가능하다.
const sampleFunc2 = () => {
    asyncFunc() // asyncFunc 함수는 Promise 객체를 반환한다
		.then(
			result => console.log(result),
			err => console.log(err)
        )
}
profile
신입사원...

0개의 댓글