Svelte 컴포넌트

2022. 11. 23. 21:17개발&TIL/Svelte

Svelte 컴포넌트의 기본적인 구조는 아래와 같다.
'.svelte' 확장자를 사용해서 파일을 컴포넌트를 정의할 수 있다.

Component Format (기본 골격)

<script>
    // JavaScript 소스가 들어가는 영역
</script>

<!-- HTML 등의 마크업이 들어가는 영역 -->

<style>
    /* 스타일 요소가 들어가는 영역 */
</style>

 


script 영역

'import' 구문을 통해서 .svelte 확장자의 다른 컴포넌트를 불러와서 사용할 수 있다.
'let' 키워드를 통한 State 값을 선언하여 변수를 선언한다.

<script>
    import Header from '.header.svelte';

    let count = 0;

    function handleClick () {
        // calling this function will trigger an
        // update if the markup references `count`
        count = count + 1;
    }
</script>

<Header>

<button on:click={handleClick}>click</button>

 

array 를 활용하는 방법

위의 코드에서 'count = count + 1;'와 같이 상태값을 재할당하는 방식으로 갱신하는 것처럼
배열에서도 .push(), .splice() 사용이후에 자동으로 업데이트 되지 않으므로 재할당이 필요하다.

'arr = arr' 또는 스프레드 연산자를 사용하여 재할당 한다.

<script>
    let arr = [0, 1];

    function handleClick () {
        // this method call does not trigger an update
        arr.push(2);
        // this assignment will trigger an update
        // if the markup references `arr`
        arr = arr
    }
</script>

 

'export' 키워드를 사용한 Props 받아오기

Svelte 에서의 'export' 키워드를 사용해서 Prop 변수 선언을 할수 있고
이는 상위컴포넌트에서 하위컴포넌트로 전달한 값을 사용할 수 있는 의미

 

ex) App.svelte

<script>
    import Child from '.child.svelte' 
    
    let name = 'tistory'; 
</script> 

<Child value={name}/>

 

ex) child.svelte

<script> 
    export let value
</script>

<!-- 부모로 전달받은 'tistory' -->
<h1> {name} </h1>

 

'const', 'class', 'function' 의 경우 readony로 외부 컴포넌트에서 사용가능

<script>
    // these are readonly
    export const thisIs = 'readonly';

    export function greet(name) {
        alert(`hello ${name}!`);
    }

    // this is a prop
    export let format = n => n.toFixed(2);
</script>

Props(properties)는 컴포넌트끼리 통신하는 기본적인 방법이며 선언
상위 컴포넌트에서 하위 컴포넌트의 데이터를 전달할때 사용

 

Props 데이터 변경

컴포넌트간에 prop 데이터는 기본적으로 단방향적인 특성을 가짐

전달되는 값은 오직 부모 컴포넌트에서만 변경이 가능

 

다만 자식 컴포넌트에서 부모 컴포넌트로 값을 변경하려면 변경 메서드를 Props로 넘겨주는 방법을 사용할 수도 있음


'$:' marks a statement as reactive

'$:' 기호를 통해서 반응성을 쉽게 구현 가능 

 

선언된 변수의 상태값을 참조하는 새로운 변수를 만들때 그 변수 앞에 '$:'를 사용하면

상태값의 변경을 감지해 자동으로 함께 변경

 

변수가 아닌 블록을 이용한 그룹화도 가능

 

<script>
	export let title;
	export let person

	// this will update `document.title` whenever
	// the `title` prop changes
	$: document.title = title;

	$: {
		console.log(`multiple statements can be combined`);
		console.log(`the current title is ${title}`);
	}

	// this will update `name` when 'person' changes
	$: ({ name } = person);

	// don't do this. it will run before the previous line
	let name2 = name;
</script>

references

1. https://svelte.dev

2.스벨트로 시작하는 웹 프런트엔드 책

 

스벨트로 시작하는 웹 프런트엔드 - YES24

웹 애플리케이션 개발을 위한 「Svelte 실전 가이드」웹 프런트엔드 기초부터 실전 SNS 프로젝트까지스벨트의 장점과 기능, 기존 프런트엔드 프레임워크와의 차이점 그리고 스벨트가 실전 프로젝

www.yes24.com

 

728x90

'개발&TIL > Svelte' 카테고리의 다른 글

Svelte Template Syntax (기본 문법)  (0) 2022.11.23
Svelte 소개  (0) 2022.07.27