0
0
mirror of https://github.com/sveltejs/svelte.git synced 2024-11-29 16:36:44 +01:00
svelte/documentation/docs/03-runtime/01-svelte.md
Rich Harris 27538fc598
tweak docs content (#8675)
* update intro

* update tutorial links

* unitalicise code spans

* Update documentation/docs/01-getting-started/01-introduction.md

Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>

* Update documentation/docs/01-getting-started/01-introduction.md

Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>

* Update documentation/docs/01-getting-started/01-introduction.md

Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>

* Update documentation/docs/01-getting-started/01-introduction.md

Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>

---------

Co-authored-by: Rich Harris <git@rich-harris.dev>
Co-authored-by: Ben McCann <322311+benmccann@users.noreply.github.com>
2023-06-01 15:44:16 -04:00

6.1 KiB

title
svelte

The svelte package exposes lifecycle functions and the context API.

onMount

EXPORT_SNIPPET: svelte#onMount

The onMount function schedules a callback to run as soon as the component has been mounted to the DOM. It must be called during the component's initialisation (but doesn't need to live inside the component; it can be called from an external module).

onMount does not run inside a server-side component.

<script>
	import { onMount } from 'svelte';

	onMount(() => {
		console.log('the component has mounted');
	});
</script>

If a function is returned from onMount, it will be called when the component is unmounted.

<script>
	import { onMount } from 'svelte';

	onMount(() => {
		const interval = setInterval(() => {
			console.log('beep');
		}, 1000);

		return () => clearInterval(interval);
	});
</script>

This behaviour will only work when the function passed to onMount synchronously returns a value. async functions always return a Promise, and as such cannot synchronously return a function.

beforeUpdate

EXPORT_SNIPPET: svelte#beforeUpdate

Schedules a callback to run immediately before the component is updated after any state change.

The first time the callback runs will be before the initial onMount

<script>
	import { beforeUpdate } from 'svelte';

	beforeUpdate(() => {
		console.log('the component is about to update');
	});
</script>

afterUpdate

EXPORT_SNIPPET: svelte#afterUpdate

Schedules a callback to run immediately after the component has been updated.

The first time the callback runs will be after the initial onMount

<script>
	import { afterUpdate } from 'svelte';

	afterUpdate(() => {
		console.log('the component just updated');
	});
</script>

onDestroy

EXPORT_SNIPPET: svelte#onDestroy

Schedules a callback to run immediately before the component is unmounted.

Out of onMount, beforeUpdate, afterUpdate and onDestroy, this is the only one that runs inside a server-side component.

<script>
	import { onDestroy } from 'svelte';

	onDestroy(() => {
		console.log('the component is being destroyed');
	});
</script>

tick

EXPORT_SNIPPET: svelte#tick

Returns a promise that resolves once any pending state changes have been applied, or in the next microtask if there are none.

<script>
	import { beforeUpdate, tick } from 'svelte';

	beforeUpdate(async () => {
		console.log('the component is about to update');
		await tick();
		console.log('the component just updated');
	});
</script>

setContext

EXPORT_SNIPPET: svelte#setContext

Associates an arbitrary context object with the current component and the specified key and returns that object. The context is then available to children of the component (including slotted content) with getContext.

Like lifecycle functions, this must be called during component initialisation.

<script>
	import { setContext } from 'svelte';

	setContext('answer', 42);
</script>

Context is not inherently reactive. If you need reactive values in context then you can pass a store into context, which will be reactive.

getContext

EXPORT_SNIPPET: svelte#getContext

Retrieves the context that belongs to the closest parent component with the specified key. Must be called during component initialisation.

<script>
	import { getContext } from 'svelte';

	const answer = getContext('answer');
</script>

hasContext

EXPORT_SNIPPET: svelte#hasContext

Checks whether a given key has been set in the context of a parent component. Must be called during component initialisation.

<script>
	import { hasContext } from 'svelte';

	if (hasContext('answer')) {
		// do something
	}
</script>

getAllContexts

EXPORT_SNIPPET: svelte#getAllContexts

Retrieves the whole context map that belongs to the closest parent component. Must be called during component initialisation. Useful, for example, if you programmatically create a component and want to pass the existing context to it.

<script>
	import { getAllContexts } from 'svelte';

	const contexts = getAllContexts();
</script>

createEventDispatcher

EXPORT_SNIPPET: svelte#createEventDispatcher

Creates an event dispatcher that can be used to dispatch component events. Event dispatchers are functions that can take two arguments: name and detail.

Component events created with createEventDispatcher create a CustomEvent. These events do not bubble. The detail argument corresponds to the CustomEvent.detail property and can contain any type of data.

<script>
	import { createEventDispatcher } from 'svelte';

	const dispatch = createEventDispatcher();
</script>

<button on:click={() => dispatch('notify', 'detail value')}>Fire Event</button>

Events dispatched from child components can be listened to in their parent. Any data provided when the event was dispatched is available on the detail property of the event object.

<script>
	function callbackFunction(event) {
		console.log(`Notify fired! Detail: ${event.detail}`);
	}
</script>

<Child on:notify={callbackFunction} />

Events can be cancelable by passing a third parameter to the dispatch function. The function returns false if the event is cancelled with event.preventDefault(), otherwise it returns true.

<script>
	import { createEventDispatcher } from 'svelte';

	const dispatch = createEventDispatcher();

	function notify() {
		const shouldContinue = dispatch('notify', 'detail value', { cancelable: true });
		if (shouldContinue) {
			// no one called preventDefault
		} else {
			// a listener called preventDefault
		}
	}
</script>

Types

TYPES: svelte