使用するAPI

今回はJSONPlaceholderというサービスのAPIを使います。
この中のtodoを取得してみます。

JSONPlaceholder

HTML

Alpine.jsだとJavaScriptもタグ中に埋め込む方法もありますが、今回はわけます。

  1. <div x-data="app()" x-cloak>
  2. <div>
  3. <input type="text" x-model="input">
  4. <button @click="handleFetch()">読み込み</button>
  5. </div>
  6. <p x-show="isLoading">読み込み中</p>
  7. <p x-show="error">データの取得に失敗しました。</p>
  8. <table x-show="Object.keys(data).length > 0">
  9. <tr>
  10. <th>ID</th>
  11. <td x-text="data.id"></td>
  12. </tr>
  13. <tr>
  14. <th>title</th>
  15. <td x-text="data.title"></td>
  16. </tr>
  17. <tr>
  18. <th>userId</th>
  19. <td x-text="data.userId"></td>
  20. </tr>
  21. </table>
  22. </div>

CSSで[x-cloak]を非表示するとちらつき防止できます。

  1. [x-cloak] {
  2. display: none
  3. }

JavaScript

Alpine.jsだとJavaScriptもタグ中に埋め込む方法もありますが、今回はわけます。

  1. <script type="text/javascript">
  2. document.addEventListener('alpine:init', () => {
  3. Alpine.data('app', () => ({
  4. input: '',
  5. data: {},
  6. error: false,
  7. isLoading: false,
  8. handleFetch() {
  9. this.isLoading = true;
  10. const requestId = this.input || '1';
  11.  
  12. fetch(`https://jsonplaceholder.typicode.com/todos/${requestId}`)
  13. .then(response => {
  14. if (! response.ok) {
  15. this.error = true;
  16. }
  17. return response.json();
  18. })
  19. .then(json => {
  20. this.isLoading = false;
  21. this.data = json;
  22. })
  23. .catch(reason => {
  24. this.error = true;
  25. });
  26. }
  27. }));
  28. });
  29. </script>