logo
🎨 前端开发

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

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2025 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572