Notes taken from a svelte tutorial. No actual code.
I took this Svelte.js - The Complete Guide (incl. Sapper.js) tutorial on Udemy and these are my cheatsheet notes.
-
$: variable = something relying on some other variable
is essentially a memoize function -
class:className={bool}
optional class -
arrays: never mutate, always recreate
-
export let
is for external props -
{#if}...{:else if}...{:else}...{/if}
-
on:event
event forwarding, for using an event passed down from above OR for getting dispatched events from below -
dispatch('eventName', data)
fromcreateEventDispatcher()
for passing data up -
slots can be default unnamed, or named, filled with default html, or empty.
-
<h1 slot="title"/>
targets<slot name="title"/>
-
<Component let:myVar>
getsmyVar
from<Component><slot myVar={myVar}/></Component>
-
Lifecycle
onMount
beforeUpdate
afterUpdate
tick
(promise)onDestroy
-
<input bind:value>
varies by input type.bind:group
is cool. -
<Component bind:myVar={localVar}/>
IF and ONLY IFtype
is not set on downstream<input/>
its binding to -
bind:this={myRef}
is ref to html element. For read. -
Use store when data shared outside of parent/child relationship
store = writeable(defaultValue) unsubscribe = store.subscribe(storeData => {}) //must unsubscribe on destroy! store.set(newVal) store.update(storeData => {}) {#each $store as item} //auto handles subscriptions <p>{$store}</p>` //auto handles subscriptions
-
readableStore = readable(storeData, set => { do some repeatable/automatic stuff; set(newStoreData); return unsubscribe fn }) unsubscibe = readableStore.subscribe(storeData => {})
-
animatedValue = tweened(value, {delay, duration, easing})
from motion -
physicsAnimatedValue = spring(value, {siffness, damping, precision})
from motion -
<div transition:fade={{delay, duration, easing, ...etc}} />
etc from transition or<div in:fade out:fly />
if you want different -
{#await fn}...{:then data}...{:catch err}...{/await}
-
<svelte:component this={Component}/>
-
<script context="module">
runs once when first instance of component is loaded -
[slug].svelte
for dynamic routing, then{slug} = page.params
-
export function preload(page){ reutrn this.fetch('')}
fetches data serverside on first page. clientside thereafter -
Preloads as you hover over a link before you even click it for super speeds
-
Lots of deploy options. take time to think.