logo

Svelte Cheat Sheet


title: Svelte date: 2025-08-16 10:30:00 background: bg-[#FF3E00] tags: - svelte - web categories: - Programming intro: | A Svelte cheat sheet with the most important concepts, functions, reactivity, and more. A complete quick reference for beginners, updated for Svelte 5. plugins: - copyCode - runCode

Getting Started

Basic Syntax

<script>
  let name = 'world';
</script>

<h1>Hello {name}!</h1>

Expressions

<script>
  let firstName = "Zehan";
  let lastName = "Khan";

  function fullName() {
    return `${firstName} ${lastName}`;
  }
</script>

<h1>Hello {fullName()}!</h1>

Attributes

<script>
  let avatarUrl = 'https://example.com/avatar.png';
</script>

<img src={avatarUrl} alt="Avatar" />
<button class="btn">Click me</button>

Functions in Markup

<script>
  function name() {
    return "Zehan";
  }
</script>

<h1>Hi {name()}!</h1>

Conditional Rendering {.col-span-2}

<script>
  let temperature = 24;
  let city = "New York";
</script>

{#if temperature >= 20}
  <p>It is {temperature}°C (Warm) in {city}</p>
{:else}
  <p>It is {temperature}°C in {city}</p>
{/if}

Note: Svelte components must always return a root element or content.

Components

Functional Component

<script>
  let { name = "User" } = $props();
</script>

<div class="UserProfile">
  <div>Hello</div>
  <div>{name}</div>
</div>

Embed an internal Component

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

<div class="UserProfile">
  <UserAvatar />
  <UserAvatar />
</div>

Embed an external Component

<script>
  import ComponentName from 'some-library';
</script>

<div class="UserProfile">
  <ComponentName />
</div>

Note: External components should be installed via npm first.

Advanced Functional Components

<script>
  let { firstName, lastName } = $props();

  function fullName() {
    return `${firstName} ${lastName}`;
  }
</script>

<p>{fullName()}</p>

Properties {.cols-2}

Passing Properties to a Component

<Student firstName="Zehan" lastName="Khan" age={23} pro={true} />

Assigning the Properties from a Component

<script>
  let { firstName, lastName, age } = $props();
</script>

<h1>{firstName} {lastName} is {age}.</h1>

State {.cols-1}

Local State

<script>
  let name = $state("Zehan");

  function updateName() {
    name = prompt("What is your name?") || name;
  }
</script>

<h1>{name}</h1>
<button onclick={updateName}>Update name</button>

Events {.cols-1}

Event Listener

<script>
  function handleClick(event) {
    event.preventDefault();
    alert("Hello World");
  }
</script>

<a href="#" onclick|preventDefault={handleClick}>
  Say Hi
</a>

Note: The most common event listeners are onclick and onsubmit.

Loops {.cols-2}

Looping through an Array

<script>
  let elements = ["one", "two", "three"];
</script>

<ul>
  {#each elements as value, index}
    <li>{value}</li>
  {/each}
</ul>

Looping through an Array of Objects

<script>
  let elements = [
    { name: "one", value: 1 },
    { name: "two", value: 2 },
    { name: "three", value: 3 }
  ];
</script>

<ul>
  {#each elements as element, index}
    <li>
      The value for {element.name} is {element.value}
    </li>
  {/each}
</ul>

Forms {.cols-1}

Form Example

<script>
  let username = $state("");
  let password = $state("");

  function handleSubmit(event) {
    event.preventDefault();
    alert(`Logging in with ${username} and ${password}`);
  }
</script>

<form onsubmit={handleSubmit}>
  <input type="text" placeholder="Username" bind:value={username} />
  <input type="password" placeholder="Password" bind:value={password} />
  <input type="submit" value="Login" />
</form>

CSS {.cols-1}

Scoped CSS

<style>
  .student {
    color: blue;
  }
</style>

<div class="student">Zehan Khan</div>

Fetching Data {.cols-1}

Fetching Data with onMount

<script>
  import { onMount } from 'svelte';
  let notifications = [];
  let loading = $state(true);

  onMount(async () => {
    const res = await fetch("https://notifications.com");
    notifications = await res.json();
    loading = false;
  });
</script>

{#if loading}
  <p>Loading notifications...</p>
{:else}
  <ul>
    {#each notifications as note}
      <li>{note.title}</li>
    {/each}
  </ul>
{/if}

Note: Use onMount for side effects like API calls.

Lifecycle Hooks {.cols-1}

onMount

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

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

beforeUpdate

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

  beforeUpdate(() => {
    console.log('Before component updates');
  });
</script>

afterUpdate

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

  afterUpdate(() => {
    console.log('After component updates');
  });
</script>

onDestroy

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

  onDestroy(() => {
    console.log('Component destroyed');
  });
</script>

Note: Svelte lifecycle functions are similar to React Hooks, but they are imported individually and used directly in the <script> block.

More Svelte Features {.cols-1}

Derived Store

// store.js
import { writable, derived } from 'svelte/store';

export const count = writable(0);
export const double = derived(count, $count => $count * 2);
// App.svelte
<script>
  import { count, double } from './store.js';
</script>

<p>Count: {$count}</p>
<p>Double: {$double}</p>

Readable Store

import { readable } from 'svelte/store';

export const time = readable(new Date(), function start(set) {
	const interval = setInterval(() => {
		set(new Date());
	}, 1000);

	return function stop() {
		clearInterval(interval);
	};
});

Reactive Declarations

<script>
  let a = $state(2);
  let b = $state(3);
  let sum = $derived(a + b);
</script>

<p>{sum}</p>

Reactive Statements with Side Effects

<script>let name = 'Zehan'; $effect(() => console.log('Name changed to', name));</script>

Bind to DOM Properties

<script>
  let text = $state('');
</script>

<textarea bind:value={text} />
<p>{text.length} characters</p>

Bind Grouped Inputs (Radio, Checkbox)

<script>
  let selected = $state('apple');
</script>

<label><input type="radio" bind:group={selected} value="apple" /> Apple</label>
<label><input type="radio" bind:group={selected} value="orange" /> Orange</label>
<p>Selected: {selected}</p>

Class and Style Directives

<script>
  let isActive = true;
</script>

<div class:active={isActive}>Toggle me</div>
<script>
  let size = 16;
</script>

<p style:font-size={`${size}px`}>Resizable text</p>

Await Blocks

<script>
  let userPromise = fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(res => res.json());
</script>

{#await userPromise}
  <p>Loading...</p>
{:then user}
  <p>{user.name}</p>
{:catch error}
  <p>Error: {error.message}</p>
{/await}

SSR with SvelteKit (Basic Example)

// +page.server.js
export async function load({ fetch }) {
	const res = await fetch('/api/data');
	const data = await res.json();
	return { data };
}
// +page.svelte
<script>
  let { data } = $props();
</script>

<h1>{data.title}</h1>

Note: Requires SvelteKit setup for SSR routes.

🎨 前端开发

Svelte

Svelte Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · 前端开发🧭 Markdown 速查🏷️ 1 个标签
#svelte
向下滚动查看内容
返回全部 Cheat Sheets

Getting Started

Basic Syntax
JS
滚动查看更多
<script>
  let name = 'world';
</script>

<h1>Hello {name}!</h1>
Expressions
JS
滚动查看更多
<script>
  let firstName = "Zehan";
  let lastName = "Khan";

  function fullName() {
    return `${firstName} ${lastName}`;
  }
</script>

<h1>Hello {fullName()}!</h1>
Attributes
JS
滚动查看更多
<script>
  let avatarUrl = 'https://example.com/avatar.png';
</script>

<img src={avatarUrl} alt="Avatar" />
<button class="btn">Click me</button>
Functions in Markup
JS
滚动查看更多
<script>
  function name() {
    return "Zehan";
  }
</script>

<h1>Hi {name()}!</h1>
Conditional Rendering
JS
滚动查看更多
<script>
  let temperature = 24;
  let city = "New York";
</script>

{#if temperature >= 20}
  <p>It is {temperature}°C (Warm) in {city}</p>
{:else}
  <p>It is {temperature}°C in {city}</p>
{/if}

Note: Svelte components must always return a root element or content.

Components

Functional Component
JS
滚动查看更多
<script>
  let { name = "User" } = $props();
</script>

<div class="UserProfile">
  <div>Hello</div>
  <div>{name}</div>
</div>
Embed an internal Component
JS
滚动查看更多
<script>
  import UserAvatar from './UserAvatar.svelte';
</script>

<div class="UserProfile">
  <UserAvatar />
  <UserAvatar />
</div>
Embed an external Component
JS
滚动查看更多
<script>
  import ComponentName from 'some-library';
</script>

<div class="UserProfile">
  <ComponentName />
</div>

Note: External components should be installed via npm first.

Advanced Functional Components
JS
滚动查看更多
<script>
  let { firstName, lastName } = $props();

  function fullName() {
    return `${firstName} ${lastName}`;
  }
</script>

<p>{fullName()}</p>

Properties

Passing Properties to a Component
JS
滚动查看更多
<Student firstName="Zehan" lastName="Khan" age={23} pro={true} />
Assigning the Properties from a Component
JS
滚动查看更多
<script>
  let { firstName, lastName, age } = $props();
</script>

<h1>{firstName} {lastName} is {age}.</h1>

State

Local State
JS
滚动查看更多
<script>
  let name = $state("Zehan");

  function updateName() {
    name = prompt("What is your name?") || name;
  }
</script>

<h1>{name}</h1>
<button onclick={updateName}>Update name</button>

Events

Event Listener
JS
滚动查看更多
<script>
  function handleClick(event) {
    event.preventDefault();
    alert("Hello World");
  }
</script>

<a href="#" onclick|preventDefault={handleClick}>
  Say Hi
</a>

Note: The most common event listeners are onclick and onsubmit.

Loops

Looping through an Array
JS
滚动查看更多
<script>
  let elements = ["one", "two", "three"];
</script>

<ul>
  {#each elements as value, index}
    <li>{value}</li>
  {/each}
</ul>
Looping through an Array of Objects
JS
滚动查看更多
<script>
  let elements = [
    { name: "one", value: 1 },
    { name: "two", value: 2 },
    { name: "three", value: 3 }
  ];
</script>

<ul>
  {#each elements as element, index}
    <li>
      The value for {element.name} is {element.value}
    </li>
  {/each}
</ul>

Forms

Form Example
JS
滚动查看更多
<script>
  let username = $state("");
  let password = $state("");

  function handleSubmit(event) {
    event.preventDefault();
    alert(`Logging in with ${username} and ${password}`);
  }
</script>

<form onsubmit={handleSubmit}>
  <input type="text" placeholder="Username" bind:value={username} />
  <input type="password" placeholder="Password" bind:value={password} />
  <input type="submit" value="Login" />
</form>

CSS

Scoped CSS
JS
滚动查看更多
<style>
  .student {
    color: blue;
  }
</style>

<div class="student">Zehan Khan</div>

Fetching Data

Fetching Data with onMount
JS
滚动查看更多
<script>
  import { onMount } from 'svelte';
  let notifications = [];
  let loading = $state(true);

  onMount(async () => {
    const res = await fetch("https://notifications.com");
    notifications = await res.json();
    loading = false;
  });
</script>

{#if loading}
  <p>Loading notifications...</p>
{:else}
  <ul>
    {#each notifications as note}
      <li>{note.title}</li>
    {/each}
  </ul>
{/if}

Note: Use onMount for side effects like API calls.

Lifecycle Hooks

onMount
JS
滚动查看更多
<script>
  import { onMount } from 'svelte';

  onMount(() => {
    console.log('Component mounted');
  });
</script>
beforeUpdate
JS
滚动查看更多
<script>
  import { beforeUpdate } from 'svelte';

  beforeUpdate(() => {
    console.log('Before component updates');
  });
</script>
afterUpdate
JS
滚动查看更多
<script>
  import { afterUpdate } from 'svelte';

  afterUpdate(() => {
    console.log('After component updates');
  });
</script>
onDestroy
JS
滚动查看更多
<script>
  import { onDestroy } from 'svelte';

  onDestroy(() => {
    console.log('Component destroyed');
  });
</script>

Note: Svelte lifecycle functions are similar to React Hooks, but they are imported individually and used directly in the <script> block.

More Svelte Features

Derived Store
JS
滚动查看更多
// store.js
import { writable, derived } from 'svelte/store';

export const count = writable(0);
export const double = derived(count, $count => $count * 2);
JS
滚动查看更多
// App.svelte
<script>
  import { count, double } from './store.js';
</script>

<p>Count: {$count}</p>
<p>Double: {$double}</p>
Readable Store
JS
滚动查看更多
import { readable } from 'svelte/store';

export const time = readable(new Date(), function start(set) {
	const interval = setInterval(() => {
		set(new Date());
	}, 1000);

	return function stop() {
		clearInterval(interval);
	};
});
Reactive Declarations
JS
滚动查看更多
<script>
  let a = $state(2);
  let b = $state(3);
  let sum = $derived(a + b);
</script>

<p>{sum}</p>
Reactive Statements with Side Effects
JS
滚动查看更多
<script>let name = 'Zehan'; $effect(() => console.log('Name changed to', name));</script>
Bind to DOM Properties
JS
滚动查看更多
<script>
  let text = $state('');
</script>

<textarea bind:value={text} />
<p>{text.length} characters</p>
Bind Grouped Inputs (Radio, Checkbox)
JS
滚动查看更多
<script>
  let selected = $state('apple');
</script>

<label><input type="radio" bind:group={selected} value="apple" /> Apple</label>
<label><input type="radio" bind:group={selected} value="orange" /> Orange</label>
<p>Selected: {selected}</p>
Class and Style Directives
JS
滚动查看更多
<script>
  let isActive = true;
</script>

<div class:active={isActive}>Toggle me</div>
JS
滚动查看更多
<script>
  let size = 16;
</script>

<p style:font-size={`${size}px`}>Resizable text</p>
Await Blocks
JS
滚动查看更多
<script>
  let userPromise = fetch('https://jsonplaceholder.typicode.com/users/1')
    .then(res => res.json());
</script>

{#await userPromise}
  <p>Loading...</p>
{:then user}
  <p>{user.name}</p>
{:catch error}
  <p>Error: {error.message}</p>
{/await}
SSR with SvelteKit (Basic Example)
JS
滚动查看更多
// +page.server.js
export async function load({ fetch }) {
	const res = await fetch('/api/data');
	const data = await res.json();
	return { data };
}
JS
滚动查看更多
// +page.svelte
<script>
  let { data } = $props();
</script>

<h1>{data.title}</h1>

Note: Requires SvelteKit setup for SSR routes.

相关 Cheat Sheets