가장 중요하면서도 기본적인 스벨트 내용을 알아보자.

선언적 렌더링

이벤트 핸들링

이번에는 이벤트 핸들링에 대해 알아본다. 먼저 스벨트에서 이벤트 핸들링 콜백을 실행하려면 omMount를 svelte에서 Import 해줘야 한다.

App.svelte

<script>
	import { onMount } from "svelte";
	let isRed = false;
	// 현재 컴포넌트가 준비되면 해당 콜백함수를 실행하겠다.
	onMount(()=> {
		const box = document.querySelector('.box');
		box.addEventListener('click', () => {
			isRed = !isRed;
		})	
	})
</script>

<div class="box" style="background-color: {isRed ? 'red' : 'orange'}">Box!</div>

<style>
	.box {
		width: 300px;
		height: 150px;
		background-color: orange;
		display:flex;
		justify-content: center;
		align-items: center;
	}
</style>

위 코드는 onMount라는 svelte API로 콜백함수가 실행시켜 box 엘리먼트를 정상적으로 찾아 동작을 실행시키는 기능을 수행한다. 해당 코드는 svelte API통해 더욱 간결하게 만들 수 있다.

App.svelte

<script>
	import { onMount } from "svelte";

	let name = 'Vicky'
	let isRed = false;

	function enter() { name = 'enter' }
	function leave() { name = 'leave' }
</script>

<h1>Hello {name}!</h1>
<div 
	class="box" 
	style="background-color: {isRed ? 'red' : 'orange'}"
	on:click={() => isRed = !isRed }
	on:mouseenter={enter}
	on:mouseleave={leave}
>
	Box!
</div>

<style>
	.box {
		width: 300px;
		height: 150px;
		cursor: pointer;
		background-color: orange;
		display:flex;
		justify-content: center;
		align-items: center;
	}
</style>

위처럼 익명함수로 전체 이벤트를 on:이벤트에 직접 바인딩해줘도 되고, 별도의 함수로 생성하여 실행시키지 않도록 추가해주도록 바인딩 처리도 가능하다.

220609-2.gif

다른 예시로, 아래와 같은 input 이벤트가 있다고 하자

<script>
	let text = ''
</script>

<h1>
	{text}
</h1>

<input 
			 type="text" 
			 on:input={(e) => { text = e.target.value }} />

<button
				on:click={() => { text = 'Vicky' }}>
	Click
</button>

해당 코드를 동작시키면 input에 추가되는 값에 따라 상단 h1 값이 변경된다. 또 Click 버튼을 클릭하면 상단 h1 값이 Vicky로 변화하는 것을 확인할 수 있다. 단, input 내부 데이터는 바뀌지 않는다.