首頁  >  文章  >  web前端  >  使用 Alpine JS 取得數據

使用 Alpine JS 取得數據

王林
王林原創
2024-07-19 14:38:47896瀏覽

這次我們將學習使用 Alpine JS 從 API 取得資料。我們將建立一個網站,顯示來自以下 API 的英超足球俱樂部清單。

Alpine JS 是一個輕量級的 Javascript 框架,我們可以用它來建立互動式網站,而無需使用 React 或 Vue 等框架。使用 Alpine JS 時,我們可以輕鬆地將 Javascript 屬性直接套用到 HTML 文件,而無需單獨編寫它們。

請建立一個名為 index.html 的 HTML 文件,然後貼上以下程式碼。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Latihan Alpine JS</title>

    <!-- Import Alpine JS -->
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

    <!-- Import Tailwind -->
    <script src="https://cdn.tailwindcss.com"></script>

    <!-- Google Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet"/>

    <style>
      * {
        font-family: "Roboto", sans-serif;
      }
    </style>
  </head>
  <body>

  </body>
</html>

接下來我們將使用 Tailwind CSS 建立一個卡片元件。

<div class="container px-4 py-12 mx-auto">
  <div class="flex flex-wrap">
    <div class="lg:w-1/4 md:w-1/2 p-4 w-full">
      <img alt="logo" class="object-cover h-56 mx-auto" src="" />
      <div class="mt-4">
        <h2 class="text-gray-500 text-xs tracking-widest mb-1"></h2>
        <h1 class="text-gray-900 text-xl font-medium"></h1>
      </div>
    </div>
  </div>
</div>

然後我們將獲取資料並將其顯示在卡片組件上。

<div class="flex flex-wrap" x-data="{ teams: [] }" x-init="fetch('https://www.thesportsdb.com/api/v1/json/3/search_all_teams.php?l=English%20Premier%20League').then(response => response.json()).then(data => { teams = data.teams })">
  <template x-for="team in teams">
    <div class="lg:w-1/4 md:w-1/2 p-4 w-full">
      <img x-bind:alt="team.idTeam" class="object-cover h-56 mx-auto" x-bind:src="team.strBadge" />
      <div class="mt-4">
        <h2 class="text-gray-500 text-xs tracking-widest mb-1" x-text="team.strLocation"></h2>
        <h1 class="text-gray-900 text-xl font-medium" x-text="team.strTeam"></h1>
      </div>
    </div>
  </template>
</div>

恭喜!您已成功使用 Alpine JS 取得 API 並將其顯示給用戶,以下是結果。

Image description

以下是對創建的程式碼的解釋。

x-data 函數用於容納 Javascript 邏輯資料直接在 HTML 標籤上運行。在此程式碼中,我們建立一個名為 team 的變量,其資料類型為數組。此變數旨在保存函數中獲取結果的資料。

x-init 旨在在元件載入之前執行初始化。在此程式碼中,我們插入一個 fetch 函數,旨在從我們先前準備的 API 端點檢索資料。然後在瀏覽器頁面顯示之前,Alpine JS 會在背景執行一次抓取過程,然後抓取的結果會被收集到一開始宣告的 team 變數中。

x-for 用於對 team 變數進行迭代過程,然後放回 team 變數。

x-bind 顯示圖像,x-text 將資料直接列印到 HTML 顯示中。

以上是使用 Alpine JS 取得數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn