Svelte 前端框架与 Runes

精选 Svelte 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。

#🚀 入门指引

#基础语法 (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)

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

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

#条件渲染 (Conditional Rendering)

<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>

#引入内部组件 (Internal Component)

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

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

#引入外部库组件 (External Component)

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

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

Note: External components should be installed via npm first.

#高级功能组件 (Advanced Components)

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

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

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

#Props 传递 (Properties)

#传递 Props 给子组件 (Passing Props)

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

#组件接收与解构 Props (Receiving Props)

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

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

#响应式状态 (State)

#本地状态 $state (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)

#事件监听器 (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)

#遍历简单数组 (Loop Array)

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

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

#遍历简单数组 (Loop 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)

#表单提交示例 (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)

#作用域隔离样式 (Scoped CSS)

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

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

#数据请求 (Fetching Data)

#数据请求 (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)

#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.

#更多 Svelte 特性 (More Features)

#派生 Store (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>

#只读 Store (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);
  };
});

#$derived 派生声明 (Reactive Declarations)

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

<p>{sum}</p>

#$effect 副作用处理 (Reactive Statements)

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

#绑定 DOM 属性 (Bind DOM Properties)

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

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

#绑定组合输入框 (Bind Grouped Inputs)

<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 与 Style 指令 (Class & Style)

<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} 异步渲染块 (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}

#SvelteKit 服务端渲染 (SSR 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.