Svelte's components can communicate with its own child components using context.
The context data cannot be used in parent components or sibling components.
Context doesn't act as responsibility, unlike store.
That is, even if the shared context data is changed, the context data gotten through getContext() is automatically changed or the screen is not automatically updated.
Context data can be any type of data, even function.
Context API
setContext() sets the data wants to share.
getContext() gets the shared data.
hasContext() checks whether the data existing.
<!-- components/Child.svelte -->
<script lang="ts">
import { setContext, getContext } from 'svelte';
import Grandchild from './Grandchild.svelte';
setContext('myData', 7);
const data = getContext('myData');
</script>
<h1>Child: {data}</h1>
<Grandchild />
I set the data named myData and set its value as 7.
It can be used by itself.
Child component calls Grandchild component as its child component, but it doesn't send the data as a form like props.
<script lang="ts">
import { getContext, hasContext } from 'svelte';
let data = 0;
if (hasContext('myData')) {
data = getContext('myData');
} else {
data = 0;
}
</script>
<h2>Grandchild: {data}</h2>
Grandchild component can use the data.
<script lang="ts">
import Child from '../components/Child.svelte';
</script>
<div>
<Child />
</div>
Module Context
<script> blocks are called whenever it is imported.
But, <script context="module"> blocks are called only once when it is imported.
It is called module context.
<!-- components/ModuleContext.svelte -->
<script context="module" lang="ts">
export let count = 0;
</script>
<script lang="ts">
export let fruit;
</script>
<div on:click={() => (count += 1)}>
{fruit}
</div>
The data in the module context is shared in all of the same components.
In addition, it can be exported to upper components.
<script lang="ts">
import ModuleContext, { count } from '../components/ModuleContext.svelte';
const fruits = ['Apple', 'Banana', 'Cherry'];
let totalCount = 0;
</script>
{#each fruits as fruit}
<ModuleContext {fruit} />
{/each}
<button on:click={() => (totalCount = count)}>
Get Total Count
</button>
<h2>Total Count: {totalCount}</h2>
Parent components can get the exported data using import.
'Web > JavaScript' 카테고리의 다른 글
[JavaScript] console object (0) | 2021.12.06 |
---|---|
[Svelte] Svelte Element (0) | 2021.12.05 |
[Svelte] Action (0) | 2021.12.02 |
[Svelte] Event Handling (0) | 2021.11.30 |
[Svelte] Slot (0) | 2021.11.28 |
댓글