Hello World - 响应式计数器

知识库
知识库文档
/tech-stacks/svelte/examples/Hello World - 响应式计数器.md

文档

Svelte 响应式计数器

目标

体验 Svelte 的"赋值即响应"魔法 —— 无需 useState/ref,直接 let count = 0 + count += 1

完整代码

src/routes/+page.svelte(SvelteKit)

<script>
  let count = 0
  let name = ''

  // Svelte 响应式声明: $: 后面表达式自动追踪依赖
  $: doubled = count * 2
  $: greeting = name ? `你好, ${name}!` : '请输入你的名字'

  function reset() {
    count = 0
    name = ''
  }
</script>

<div class="container">
  <h1>🟠 Svelte 入门</h1>

  <!-- 计数器 -->
  <section class="card">
    <h2>计数器</h2>
    <p class="count">{count}</p>
    <p class="hint">两倍值: {doubled}</p>
    <div class="buttons">
      <button on:click={() => count -= 1}>-1</button>
      <button on:click={reset}>重置</button>
      <button on:click={() => count += 1}>+1</button>
    </div>
  </section>

  <!-- 响应式输入 -->
  <section class="card">
    <h2>响应式输入</h2>
    <input
      type="text"
      bind:value={name}
      placeholder="输入名字..."
      class="input"
    />
    <p class="greeting">{greeting}</p>
  </section>

  <!-- 条件渲染 -->
  <section class="card">
    <h2>条件与循环</h2>
    {#if count > 10}
      <p class="warn">🔥 计数值很大了!</p>
    {:else if count < -5}
      <p class="warn">❄️ 计数值很小...</p>
    {:else}
      <p>计数值在正常范围</p>
    {/if}
  </section>
</div>

<style>
  .container { max-width: 400px; margin: 2rem auto; font-family: system-ui; }
  h1 { color: #ff3e00; }
  .card { border: 1px solid #e5e7eb; border-radius: 12px; padding: 20px; margin-bottom: 16px; }
  .count { font-size: 3rem; font-weight: bold; margin: 0.5rem 0; }
  .hint { color: #94a3b8; }
  .buttons { display: flex; gap: 8px; }
  button { padding: 8px 16px; background: #ff3e00; color: white; border: none; border-radius: 6px; cursor: pointer; }
  .input { width: 100%; padding: 8px 12px; border: 2px solid #e2e8f0; border-radius: 8px; font-size: 1rem; box-sizing: border-box; }
  .greeting { font-size: 1.2rem; margin-top: 8px; }
  .warn { color: #f59e0b; font-weight: bold; }
</style>

运行

npm install &;& npm run dev
# → http://localhost:5173

预期输出

  • 点击按钮 count 变化,doubled 自动更新
  • 输入名字,问候语实时响应
  • 计数 >10 或 <-5 时条件渲染提示

信息

路径
/tech-stacks/svelte/examples/Hello World - 响应式计数器.md
更新时间
2026/5/30