汇率转换

在本章中,我们将构建汇率转换工具。

创建页面

创建 src/pages/currency-converter.astro

---

---

<MainLayout>
  <h1>汇率转换</h1>
  <form id="converter">
    <input type="number" id="amount" placeholder="金额" />
    <select id="from">
      <option value="USD">USD</option>
      <option value="CNY">CNY</option>
    </select>
    <select id="to">
      <option value="CNY">CNY</option>
      <option value="USD">USD</option>
    </select>
    <button type="submit">转换</button>
  </form>
  <div id="result"></div>
</MainLayout>

添加交互

使用客户端脚本:

<script is:inline>
document.getElementById('converter').addEventListener('submit', async (e) => {
  e.preventDefault();
  const amount = document.getElementById('amount').value;
  const from = document.getElementById('from').value;
  const to = document.getElementById('to').value;
  
  const response = await fetch(
    `https://api.exchangerate-api.com/v4/latest/${from}`
  );
  const data = await response.json();
  const rate = data.rates[to];
  const result = amount * rate;
  
  document.getElementById('result').textContent = `${amount} ${from} = ${result.toFixed(2)} ${to}`;
});
</script>

下一步

继续添加更多工具。