📘
만들면서 배우는 svelte
  • 1. svelte 소개
  • 2. 개발환경 설정
    • 수업 코드 및 문서 가이드 안내
    • 비주얼스튜디오 & REPL
    • 설치
  • 3. 컴포넌트 - 기본
    • 앱 구조 설명 : main.js, App.js, 폴더구조
    • 컴포넌트 기본 : 레이아웃 샘플 구성(여러 component 연동)
    • state
    • reactivity
    • 컴포넌트 통신방법용 기본 앱 코드
    • 컴포넌트 통신방법 1 : props
    • 컴포넌트 통신방법 2 : dispatch
    • 컴포넌트 통신방법 3 : context API
    • 컴포넌트 통신방법 4 : store
  • 4. 컴포넌트 - 템플릿 제어
    • {#if ...}
    • {#each ...}
    • bind
    • event
    • slot
    • lifecycle (생명주기)
  • 5. 스타일 및 효과
    • 동적 css 적용방법
    • transition : 화면전환
    • todo store 적용 3 : 컴포넌트에 store 연동
  • 6. 실습 1 - TODO 만들기
  • 7. 실습 2 - store를 통한 todo 리팩토링
  • 8. 라우터 - routify
    • 소개 & 설치
    • 라우팅 생성
    • 링크 생성
    • parameter 전달 및 받기
    • todo 서비스에 적용
  • 9. ajax 처리
    • fetch와 {#await ..} 적용
    • axios 적용
  • 10 . 기타
    • 경로 쉽게 적용하기
    • javascript 배열 조작 메서드
    • 화살표 함수
Powered by GitBook
On this page

Was this helpful?

  1. 3. 컴포넌트 - 기본

컴포넌트 통신방법 3 : context API

context를 이용한 전달

prop를 다른 하위 컴포넌트로 값을 전달 가능하지만, 이 방법이 효율적이지 않을 때가 있습니다.

대표적인 예가 구성요소의 컴포넌트가 바로 하위가 아닌 좀 더 깊은 구조의 컴포넌트에 값을 전달할 경우인 때입니다. 이럴때 사용가능한 기능이 바로 context API입니다.

  • 구성 트리리 이미지 참조

svelte에서는 getContext로 값을 담고, setCntext로 값을 받아 올 수 잇습니다. 이 기능이 좋은 점은 값을 전달하기 위해 계속해서 컴포넌트로 prop를 전달할 필요가 없다는 것입니다.

  • setContext - 전달

<script>
import {setContext} from 'svelte'

const setValues = {
	a: 1,
	b: 2
}

setContext('setKey', setValue)

...
  • getContext - 받기

<script>
import { getContext } from 'svelte'

const getValue = getContext('setKey')

</script>

a: { getValue.a }
b: { getValue.b } 

예제 context API

  • app.svelte

<script>
import { setContext } from 'svelte'

import PanelComponent from './components/panelComponent.svelte'

let count = 10

function incrementCount(event) {
	count ++
}

setContext('incrementCount', incrementCount)
setContext('count', count)

</script>

<PanelComponent {count} />
  • panelComponent.svelte

<script>
import ButtonComponent from './buttonComponent.svelte'

export let count
</script>

<div class="penal">
  <h1>{count}</h1>
  
  <ButtonComponent {count}  />
  
</div>

<style>
  .penal {
    padding: 20px;
    display:flex;
    flex-direction: column;
    justify-items: center;
    justify-content: space-around;
    align-items: center;
    height: 500px;
    width:400px;
    background: #e2e2e2;
    border: 1px solid #777777;
  }
</style>
  • buttonComponent.svelte

<script>
import { getContext } from 'svelte'
// export let count

let handleIncrementCount = getContext('incrementCount')
let count = getContext('count')
</script>

<button on:click={handleIncrementCount} >
  increment count [{count}]
</button>

Previous컴포넌트 통신방법 2 : dispatchNext컴포넌트 통신방법 4 : store

Last updated 4 years ago

Was this helpful?

[만들면서 배우는 Svelte]
만들면서 배우는 svelte