Svelte¶
A svelte page contains in one file:
- JavaScript
- Template (HTML)
- Styles
The CheatSheet shows all elements and how to use them.
Script¶
A script block is used to load components into this one.
Export Variables¶
Svelte uses the export keyword before a variable declaration to make it accessible to consumers of the component. If it is initialized with a value, this will be the default if nothing specified. Exporting a const, classor function will be readonly from the outside.
export let title = 'Home'
Reactive Variables¶
Locally declared variables, which are used in the template are reactive. Changing the value will also change it at the position it is used in template. This is done if a new value is assigned. If you change a value without assignment like push() or splice() this won't work, so you have to reassign the variable like:
let arr = [5];
funclion click() {
arr.push(6); // variable is not assigned
arr = arr; // to trigger change
}
You can also mark variables as reactive which are not locally defined with $: like:
$: setup.title = title;
Module Script¶
A <script> tag with a context="module" attribute runs once when the module first is loaded, not every time the component is used.
Template¶
A capitalized tag, such as <Button> indicates a component, which should be imported with this name in the script. Attribute values or node content can contain JavaScript expressions using curly braces: <Button label={text} />. Attributes are completely removed if their value is false, null or undefined. You can use quotes around the value to prevent syntax highlighting problems. If the attribute name and value name matches you can only write the value like {name}.
Control Structures¶
The first control command starts with # while the following start with : and ends at one starting with /:
{#if X === 1}...{/if}- conditional value{#if X === 1}...{:else if X > 1}...{:else}...{/if}{#each expression as name}...{/each}{#each expression as name, index}...{/each}{#each expression as name (key)}...{/each}{#each expression as name, index (key)}...{/each}{#each expression as name}...{:else}...{/each}{#await expression}...{:then name}...{:catch name}...{/await}{#await expression}...{:then name}...{/await}{#await expression then name}...{/await}{#await expression catch name}...{/await}{#key expression}...{/key}- recreate element on value change{@html ...}- don't escape html characters{@debug}- output statement on any state change{@debug var1, var2, ..., varN}- output variable content to console if devtools are active
Events¶
on:eventname={handler}- calling handleron:eventname|modifiers={handler}- with one or multiple modifierson:eventname- forward event to consumer component
The following modifiers are available:
preventDefault— calls event.preventDefault() before running the handlerstopPropagation— calls event.stopPropagation(), preventing the event reaching the next elementpassive— improves scrolling performance on touch/wheel events (Svelte will add it automatically where it's safe to do so)nonpassive— explicitly set passive: falsecapture— fires the handler during the capture phase instead of the bubbling phaseonce— remove the handler after the first time it runsself— only trigger handler if event.target is the element itselftrusted— only trigger handler if event.isTrusted is true. I.e. if the event is triggered by a user action.
An element with transitions will dispatch the following events in addition to any standard DOM events:
introstartintroendoutrostartoutroend
Bindings¶
Using bind:property={variable} allows to let bind a component property back to it's parent:
<details> elements support binding to the open property.
Elements with the contenteditable attribute support innerHTML and textContent bindings.
Media elements (<audio> and <video>) have their own set of bindings:
duration(readonly) — the total duration of the video, in secondsbuffered(readonly) — an array of {start, end} objectsplayed(readonly) — dittoseekable(readonly) — dittoseeking(readonly) — booleanended(readonly) — boolean
...and five two-way bindings:
currentTime— the current playback time in the video, in secondsplaybackRate— how fast or slow to play the video, where 1 is 'normal'paused— this one should be self-explanatoryvolume— a value between 0 and 1muted— a boolean value indicating whether the player is muted
Block-level elements have 4 readonly bindings, measured using a technique similar to:
clientWidthclientHeightoffsetWidthoffsetHeight
In radio or checkbox input you can use the bind:group={variable}.
To get a binding to the component itself use bind:this={dom_node}.
Class and Style¶
class:name={value}orclass:namewill set the class if value istrue.--style-props="anycssvalue"this will set the direct css styles.
Actions¶
Actions are functions that are called when an element is created using use:action or use:action={parameters}. The corresponding JavaScript will look like:
action = (node: HTMLElement, parameters: any) => {
update?: (parameters: any) => void,
destroy?: () => void
}
Transitions¶
transition:fntransition:fn={params}transition:fn|localtransition:fn|local={params}in:fnin:fn={params}in:fn|localin:fn|local={params}out:fnout:fn={params}out:fn|localout:fn|local={params}
transition = (node: HTMLElement, params: any) => {
delay?: number,
duration?: number,
easing?: (t: number) => number,
css?: (t: number, u: number) => string,
tick?: (t: number, u: number) => void
}
Animations¶
Animations run if the index of an element in an each loop changes.
animate:nameanimate:name={params}
animation = (node: HTMLElement, { from: DOMRect, to: DOMRect } , params: any) => {
delay?: number,
duration?: number,
easing?: (t: number) => number,
css?: (t: number, u: number) => string,
tick?: (t: number, u: number) => void
}
DOMRect {
bottom: number,
height: number,
left: number,
right: number,
top: number,
width: number,
x: number,
y: number
}
Slots¶
This defines a place to inject content.
<slot><!-- optional fallback --></slot><slot name="x"><!-- optional fallback --></slot><slot prop={value}></slot>
Special¶
<svelte:component this={expression}/>- render component dynamically<svelte:window on:event={handler}/>- to add listener to window object<svelte:window bind:prop={value}/><svelte:body on:event={handler}/>- to add listener to body<svelte:head>...</svelte:head>- insert into html header<svelte:options option={value}/>- specify compiler options for component<svelte:fragment>- used to define a named slot without a visible html element like div
Styles¶
Styles within a component are always scoped, meaning are only valid within the component and not for the whole page.
To apply styles to a selector globally, use the :global(...) modifier.
Store¶
The store is a central component to store current state over all pages. You can create multiple stores which may be readable or writable. Every object that correctly implements subscribe, unsubscribe, and (optionally) set is a valid store.
To access a store you can access its value inside a component by prefixing it with the $ character. The $ sign makes the variable reactive and assignments with it will use the get() and set() methods. The prefixed variable gives you the value inside the store. Behind the scene, Svelte makes a subscription to the store (i.e. calls its subscribe method) when your component is created, and unsubscribes when it is destroyed.
Code in reactive blocks $: is kept in sync and reruns when (reactive) variables they contain change. You can also assign it to a block of code:
$: {
...
}