DEV.log

context-api 본문

Svelte/tutorial

context-api

magnae2016 2022. 2. 1. 12:41
<!-- App.svelte -->
<script>
	import Map from './Map.svelte';
	import MapMarker from './MapMarker.svelte';
</script>

<Map lat={35} lon={-84} zoom={3.5}>
	<MapMarker lat={37.8225} lon={-122.0024} label="Svelte Body Shaping"/>
	<MapMarker lat={33.8981} lon={-118.4169} label="Svelte Barbershop & Essentials"/>
	<MapMarker lat={29.7230} lon={-95.4189} label="Svelte Waxing Studio"/>
	<MapMarker lat={28.3378} lon={-81.3966} label="Svelte 30 Nutritional Consultants"/>
	<MapMarker lat={40.6483} lon={-74.0237} label="Svelte Brands LLC"/>
	<MapMarker lat={40.6986} lon={-74.4100} label="Svelte Medical Systems"/>
</Map>
<!-- Map.svelte -->
<script>
	import { onDestroy, setContext } from 'svelte';
	import { mapbox, key } from './mapbox.js';

	setContext(key, {
		getMap: () => map,
	});

	export let lat;
	export let lon;
	export let zoom;

	let container;
	let map;

	function load() {
		map = new mapbox.Map({
			container,
			style: 'mapbox://styles/mapbox/streets-v9',
			center: [lon, lat],
			zoom,
		});
	}

	onDestroy(() => {
		if (map) map.remove();
	});
</script>

<!-- this special element will be explained in a later section -->
<svelte:head>
	<link
		rel="stylesheet"
		href="https://unpkg.com/mapbox-gl/dist/mapbox-gl.css"
		on:load={load}
	/>
</svelte:head>

<div bind:this={container}>
	{#if map}
		<slot />
	{/if}
</div>

<style>
	div {
		width: 100%;
		height: 100%;
	}
</style>
<!-- MapMarker.svelte -->
<script>
	import { getContext } from 'svelte';
	import { mapbox, key } from './mapbox.js';

	const { getMap } = getContext(key);
	const map = getMap();

	export let lat;
	export let lon;
	export let label;

	const popup = new mapbox.Popup({ offset: 25 })
		.setText(label);

	const marker = new mapbox.Marker()
		.setLngLat([lon, lat])
		.setPopup(popup)
		.addTo(map);
</script>
// mapbox.js
import mapbox from 'mapbox-gl';

// https://docs.mapbox.com/help/glossary/access-token/
mapbox.accessToken = MAPBOX_ACCESS_TOKEN;

const key = Symbol();

export { mapbox, key };

 

https://svelte.dev/tutorial/context-api

 

Context API / setContext and getContext • Svelte Tutorial

Context API / setContext and getContext a. Basicsb. Adding datac. Dynamic attributesd. Stylinge. Nested componentsf. HTML tagsg. Making an appa. Assignmentsb. Declarationsc. Statementsd. Updating arrays and objectsa. Declaring propsb. Default valuesc. Spre

svelte.dev

 

'Svelte > tutorial' 카테고리의 다른 글

sharing-code  (0) 2022.02.01
context-api  (0) 2022.02.01
slot-props  (0) 2022.02.01
optional-slots  (0) 2022.02.01
named-slots  (0) 2022.02.01
slots  (0) 2022.02.01
0 Comments
댓글쓰기 폼