티스토리 뷰

TIL

TIL 230326 Svelte 공부 시작!

2021bong 2023. 3. 26. 22:56

svelte를 공부를 시작해보겠습니다~😀

svelte가 좋은 점

1. 코드가 적다.

React.js의 useState나 Vue.js의 data()와 같은 코드들이 없이 let, const로 state 선언이 가능하다.

 

2. 가상돔이 없다.

svelte는 React나 Vue처럼 컴파일시 번들링 된 엔진이 들어가지 않고 바닐라 자바스크립트 코드로 변환해준다. 그래서 코드량이 적다.

파일 크기 (출처 : https://medium.com/dailyjs/a-realworld-comparison-of-front-end-frameworks-2020-4e50655fe4c1)

 

3. 반응성 코드

let 으로 선언한 state에서 파생되는 다른 state를 만들고 싶을 때 $:와 같은 반응성 함수 키워드를 붙이면 바로 만들 수 있다. 코드가 짧고 바로 적용되는 반응적인 코드이다.

 

템플릿 프로젝트 생성

svelte에서 권하는 방법 중에 템플릿 프로젝트를 생성하는 방법으로 공부를 진행하려고 한다.

npx degit svelte/template [프로젝트 이름]

 

기본적인 파일 구조 및 코드

  • public : 빌드 파일
  • scripts : 타입스크립트 설정을 진행할 때 사용
  • src : 작성하는 코드들이 들어있는 폴더

 

React에 root.render나 Vue에서 creatApp와 같은 역할을 하는 것 같다.

// main.js
import App from './App.svelte';

const app = new App({
	target: document.body,
	props: {
		name: 'world'
	}
});

export default app;

 

svelte의 확장자는 .svelte이며 컴포넌트이름의 첫글자는 대문자로 해야한다.

<script>에 js, <main>에 html, <style>에 css을 적어주면 된다.

 

// App.svelte
<script>
	export let name;
</script>

<main>
	<h1>Hello {name}!</h1>
	<p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
</main>

<style>
	main {
		text-align: center;
		padding: 1em;
		max-width: 240px;
		margin: 0 auto;
	}

	h1 {
		color: #ff3e00;
		text-transform: uppercase;
		font-size: 4em;
		font-weight: 100;
	}

	@media (min-width: 640px) {
		main {
			max-width: none;
		}
	}
</style>

 

useState나 data()와 같은 state는 바닐라 자바스크립트와 똑같이 선언하면 된다.

<script>
	let name = 'bong';
</script>

 

{}를 사용해서 변수를 넣어줄 수 있다. 

<script>
	let name = 'bong';
</script>

<main>
  <p>{name}</p>
</main>

 

이벤트는 on:키워드를 사용하면 되는 것 같다.

<script>
  let name = 'bong'
  let like = 0
  const handleUpLike = () => like = like + 1
</script>

<main>
  <p>{name}</p>
  <p>{like}</p>
  <button on:click={handleUpLike}>LIKE</button>
</main>

 

반복문을 돌리고 싶을 때는 each 키워드를 쓰면 된다. 배열도 가능하고 객체도 가능하다.

// syntax
{#each 변수명 as 인자}
  <p>{인자}</p>
{/each}
<script>
  let name = 'bong'
  let like = 0
  const handleUpLike = () => like = like + 1

  let otherUser = ['kim','lee','park']
</script>

<main>
  <p>{name}</p>
  <p>{like}</p>
  <button on:click={handleUpLike}>LIKE</button>
  <p>other user</p>
  {#each otherUser as user}
    <p>{user}</p>
  {/each}
</main>

 

뭔가를 추가할 때는 함수안에서 변수에 새로운 변수의 값을 재할당 해주면 된다.

<script>
  let name = 'bong'
  let like = 0
  const handleUpLike = () => like = like + 1

  let otherUser = ['kim','lee','park']
  const addNewUser = () => {
    otherUser = [...otherUser, 'New user']
  }
</script>

<main>
  <p>{name}</p>
  <p>{like}</p>
  <button on:click={handleUpLike}>LIKE</button>
  <p>other user</p>
  {#each otherUser as user}
    <p>{user}</p>
  {/each}
  <button on:click={addNewUser}>ADD USER</button>
</main>

 

변수에 따른 조건부 렌더링도 가능하다.

<script>
  let name = 'bong'
  let like = 0
  const handleUpLike = () => like = like + 1

  let otherUser = ['kim','lee','park']
  const addNewUser = () => {
    otherUser = [...otherUser, 'New user']
  }
</script>

<main>
  <span class="user-title">{like > 10 ? 'popular':'regular'}</span>
  <p>{name}</p>
  <p>{like}</p>
  <button on:click={handleUpLike}>LIKE</button>
  <p>other user</p>
  {#each otherUser as user}
    <p>{user}</p>
  {/each}
  <button on:click={addNewUser}>ADD USER</button>
</main>

 

$:를 사용해서 손쉽게 파생된 값을 만들 수 있다. 하지만 원본의 변화에 따라 바뀌므로 push나 slice를 사용했을 때는 재할당을 통해 변경을 알려줘야한다.

// syntax
$:변수명 = 값
<script>
  let name = 'bong'
  let like = 0
  $:leftForPopular = 10 - like
  const handleUpLike = () => like = like + 1

  let otherUser = ['kim','lee','park']
  const addNewUser = () => {
    otherUser = [...otherUser, 'New user']
  }
</script>

<main>
  <p class="user-title">{like < 10 ? `popular user까지 ${leftForPopular} 남았습니다.`:'축하합니다. popular user 입니다!'}</p>
  <p>{name}</p>
  <p>{like}</p>
  <button on:click={handleUpLike}>LIKE</button>
  <p>other user</p>
  {#each otherUser as user}
    <p>{user}</p>
  {/each}
  <button on:click={addNewUser}>ADD USER</button>
</main>

 

조건절을 만들 수도 있다.

// syntax
$:if(조건문){실행할 동작}
<script>
  let name = 'bong'
  let like = 0
  $:leftForPopular = 10 - like
  $:if(like === 10) {
    alert('축하합니다. popular user가 되셨습니다!')
  }
  const handleUpLike = () => like = like + 1

  let otherUser = ['kim','lee','park']
  const addNewUser = () => {
    otherUser = [...otherUser, 'New user']
  }
</script>

 

이벤트를 사용할 때는 on:키워드만 다르고 React와 비슷한 것 같다. 파라미터로 event도 받을 수 있고 인라인도 가능하다.

<script>
  let otherUser = ['kim','lee','park']
  const addNewUser = (e) => {
    console.log(e)
    otherUser = [...otherUser, 'New user']
  }
</script>

<main>
  <button on:click={addNewUser}>ADD USER</button>
</main>
<script>
  let otherUser = ['kim','lee','park']
  const addNewUser = (e) => {
    console.log(e)
    otherUser = [...otherUser, 'New user']
  }
</script>

<main>
  <button on:click={addNewUser}>ADD USER</button>
  <button on:click={(e)=>console.log(e)}>ADD USER</button>
</main>

 

인자를 전달할 때는 무조건 인라인형식으로 작성해야한다.

<button on:click={()=>addNewUser(user)}>ADD USER</button>

 

이벤트 수식어 (modifiers)

이벤트를 제어하기 위해서 사용하는 once, preventDefault 등의 수식어들이 있다. 동시에 여러개도 사용가능하다.

// syntax
on:이벤트명|수식어[|수식어|수식어]={함수}

 

props

props 전달은 React와 방식이 비슷하다. 직접 넣어줄 수도 있고 변수를 넣어줄 수도 있다.

// syntax
<자식컴포넌트 props이름 = {값} >
// App.svelte
<script>
  import Child from './Child.svelte';
  let date = new Date()
</script>

<main>
  <Child date={date}>
  <Child now={new Date()}>
</main>

이렇게 props를 전달하는 것도 가능하다.

// App.svelte
<script>
  import Child from './Child.svelte';
  let date = new Date()
  const myFunction = () => console.log('yeah!')
</script>

<main>
  <Child {date} {myFunction}>
</main>

 

props는 자식컴포넌트에서 export 키워드를 사용해 쓰면 된다. 함수도 같은 방식으로 하면 된다. 데이터가 부모에서 받아오는 단방향 형식이라서 export 할 때 const를 사용하면 에러가 나는 것 같다.

// Child.svelte
<script>
  export let date;
  export let now;
</script>

<main>
  <p>{date}</p>
  <p>{now}</p>
</main>

 

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함