Svelte

description: Frontend Javascript & Typescript

lang: FR

Syntaxe

Variables

<script>
    let name = "Mon nom"
</script>

<h1>Tu es {name}</h1>
<script>
    let src = "./file.gif";
</script>

<img src={src} />
<!-- est équivalent à -->
<img {src} />
<script>
    let balise = "<strong>Code en gras</strong>
</script>

<p>{@html balise}</p>

Style

<p>Coucou</p>

<style>
    p {
        background-color: green;
    }
</style>

Reactivité

<button on:click={increment}>
	Clicked {count}
	{count === 1 ? 'time' : 'times'}
</button>
<script>
    let name = "truc";
</script>

<input bind:value={name} />
<script>
    let count = 0;
    $: doubled = count * 2
</script>
<script>
$: {
    // Put something here
}

$: if (condition) {
    // Do something!
} /* else {

} */
</script>
<script>
let foo = obj.foo;
foo.bar = "bar"; // Don't redraw obj
</script>

Export

    <script>
        export let anwser = "Default value";
    </script>
    const obj = {
        answer: 42
    };

    <Nested {...obj} />

Structures de contrôles

{#if condition}
    <!-- Code html -->
{/if}
{#if condition}
    <!-- Code html -->
{:else}
    <!-- Autre code html -->
{/if}
{#if condition}
    <!-- Code html -->
{:else if condition}
    <!-- Code html 2 -->
{:else}
    <!-- Code html 3 -->
{/if}

{#each iterables as iterable}
    <!-- Code html -->
{/each}
{#each iterables as iterable, index}
    <!-- Code html -->
{/each}
{#each things as thing (thing.id)}
	<Thing name={thing.name}/>
{/each}

Asynchrone

{#await promise}
    <!-- Code html d'attente -->
{:then res}
    <!-- Code html de résolution -->
{:catch error}
    <!-- Code html de gestion d'erreur -->
{/await}
{#await promise then number}
    <!-- Code html -->
{/await}

Cycle de vie

Stores

import { writable } from 'svelte/store';

export const count = writable(0);
const unsubscribe = count.subscribe((value) => {
    // Action
})
<script>
let v = $count
</script>
<!-- Ou dans le HTML -->
<h1>La valeur est {$count}</h1>
export const time = readable(new Date(), function start(set) {
	const interval = setInterval(() => {
		set(new Date());
	}, 1000);

	return function stop() {
		clearInterval(interval);
	};
});
const start = new Date();

export const elapsed = derived(
	time,
	($time) => Math.round(($time - start) / 1000)
);
function createCount() {
	const { subscribe, set, update } = writable(0);

	return {
		subscribe,
		increment: () => update((n) => n + 1),
		decrement: () => update((n) => n - 1),
		reset: () => set(0)
	};
}