Hello World - 计数器与双向绑定

知识库
知识库文档
/tech-stacks/alpinejs/examples/Hello World - 计数器与双向绑定.md

文档

Alpine.js Hello World — 计数器与双向绑定

目标

用最小的 HTML 代码展示 Alpine.js 核心特性:声明式数据、双向绑定、条件渲染和事件处理。

完整代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <title>Alpine.js Demo</title>
  <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.13.0/dist/cdn.min.js"></script>
  <style>
    body {
      font-family: 'Inter', -apple-system, sans-serif;
      max-width: 500px; margin: 60px auto;
      background: #f8fafc; color: #1e293b;
    }
    .card {
      background: white; border-radius: 16px;
      padding: 2rem; box-shadow: 0 4px 24px rgba(0,0,0,0.06);
    }
    button {
      padding: 10px 24px; border: none; border-radius: 8px;
      font-size: 1rem; cursor: pointer; margin: 4px;
      transition: 0.2s;
    }
    .btn-inc { background: #10b981; color: white; }
    .btn-dec { background: #ef4444; color: white; }
    .btn-reset { background: #64748b; color: white; }
    button:hover { transform: translateY(-1px); }
    .count { font-size: 3rem; font-weight: 700; text-align: center; margin: 1rem 0; }
    input { width: 100%; padding: 10px; border: 2px solid #e2e8f0;
      border-radius: 8px; font-size: 1rem; margin: 8px 0; }
    .message { color: #6366f1; font-weight: 500; }
  </style>
</head>
<body>
  <div class="card" x-data="{
    count: 0,
    name: '朋友',
    showMessage: true,
    get greeting() {
      return \`你好,\${this.name}!\`
    }
  }">
    <h1>⚡ Alpine.js Demo</h1>

    <!-- 双向绑定 -->
    <input
      type="text"
      x-model="name"
      placeholder="输入你的名字..."
    />

    <!-- 响应式文本 -->
    <p class="message" x-text="greeting"></p>

    <!-- 计数器 -->
    <div class="count" x-text="count"></div>

    <div style="text-align:center">
      <button class="btn-inc" @click="count++">+ 1</button>
      <button class="btn-dec" @click="count--">- 1</button>
      <button class="btn-reset" @click="count = 0">重置</button>
    </div>

    <!-- 条件渲染 -->
    <div x-show="count >= 10" style="margin-top:16px;padding:12px;background:#fef3c7;border-radius:8px">
      🎉 你已经点击了 <strong x-text="count"></strong> 次!了不起!
    </div>

    <!-- Toggle -->
    <button style="margin-top:12px;background:#8b5cf6;color:#fff;width:100%"
      @click="showMessage = !showMessage">
      切换消息显示
    </button>
    <p x-show="showMessage" style="text-align:center;color:#10b981;">
      ✅ 这行文字由 x-show 控制显示
    </p>
  </div>
</body>
</html>

运行步骤

  1. 将代码保存为 index.html
  2. 用浏览器直接打开即可运行(无需服务器)

预期输出

  • 输入框文字与问候语实时同步(x-model 双向绑定)
  • 点击按钮改变计数值(@click 事件处理)
  • 计数 ≥10 时出现庆祝提示(x-show 条件渲染)
  • 可切换消息可见性

信息

路径
/tech-stacks/alpinejs/examples/Hello World - 计数器与双向绑定.md
更新时间
2026/5/31