컴포넌트 통신방법 4 : store

예제 - store

  • store.js

import  { writable } from 'svelte/store'

let value = 0

export const count = writable(value)
  • App.svelte

<script>
import { setContext } from 'svelte'

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

</script>

<PanelComponent />
  • panelComponent.svelte

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

import { count } from '../store'
</script>

<div class="penal">
  <h1>{$count}</h1>
  
  <ButtonComponent  />
  
</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 { count } from '../store'

function handleIncrementCount() {
  count.update(count => count + 1)
}

</script>

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

[만들면서 배우는 Svelte]

Last updated