Skip to the content.

Svelte Basics

Quick

File Structure

<script>
  [CODE GOES HERE]
</script>

[MARKUP GOES HERE]

<style>
  [CSS GOES HERE]
</style>

Show variable value in HTML like so :

<h1> {variable} <h1>

Shorthand attributes if attribute and variable name have the same name :

<img src={src} /> = <img {src} />

Import with

<script>
  import Nested from './Nested.svelte';
</script>

<Nested />

Function

function incrementCount() {
  count += 1;
}

Event

Event handler

Creating And Passing Event

Reactive values

let count = 0;
$: doubled = count * 2;

$: if (count >= 10) {
  alert('count is dangerously high!');
  count = 9;
}

Binding

Props with default value

If you have an object of properties, you can ‘spread’ them onto a component instead of specifying each one:

<Info {...pkg} />

Globals

Logic

If Logic

Loop Logic

Await block

Every component has a lifecycle that starts when it is created, and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle.

Store

A store is simply an object with a subscribe method that allows interested parties to be notified whenever the store value changes

Custom store

Store binding

Motion

They work like store that allow animation