Skip to content

Svelte

基本语法

Reactivity

<script>
let numbers = $state([1, 2, 3, 4]);
let total = $derived(numbers.reduce((t, n) => t + n, 0));
const addNumber = () => numbers.push(numbers.length + 1);
</script>
<p>{number.join()} {total}</p>
<button onclick={addNumber}></button>
  • $state()
  • $derived() 由状态派生
  • $inspect() 在值改变时自动输出
  • $effect()

Props

<script>
const pkg = {
  name: 'cool',
  version: 5,
};
let { name = 'cool' } = $props();
let { name, ...pkg } = $props();
let pkg = $props();
</script>
<PackageInfo {...pkg} />
- $props() 声明部件的 properties,可设置默认值

Logic

{#if count > 10}
  <p>If {count}</p>
{:else if count < 5}
  <p>Else If {count}</p>
{:else}
  <p>Else {count}</p>
{/if}

<div>
  {#each colors as color, i (color)}
    <button
      style="background: {color}"
    >{i + 1} 
    </button>
  {/each}
</div>

{#await promise}
  <p>...rolling</p>
{:then number}
  <p>{number}</p>
{:catch error}
  <p>{error.message}</p>
{/await}
  • 在 each 循环中标明 key 来更新整个个体

Events