使用するAPI
今回はJSONPlaceholderというサービスのAPIを使います。
この中のtodoを取得してみます。
JSONPlaceholder
HTML
Alpine.jsだとJavaScriptもタグ中に埋め込む方法もありますが、今回はわけます。
<div x-data="app()" x-cloak>
<div>
<input type="text" x-model="input">
<button @click="handleFetch()">読み込み</button>
</div>
<p x-show="isLoading">読み込み中</p>
<p x-show="error">データの取得に失敗しました。</p>
<table x-show="Object.keys(data).length > 0">
<tr>
<th>ID</th>
<td x-text="data.id"></td>
</tr>
<tr>
<th>title</th>
<td x-text="data.title"></td>
</tr>
<tr>
<th>userId</th>
<td x-text="data.userId"></td>
</tr>
</table>
</div>
CSSで[x-cloak]を非表示するとちらつき防止できます。
[x-cloak] {
display: none
}
JavaScript
Alpine.jsだとJavaScriptもタグ中に埋め込む方法もありますが、今回はわけます。
<script type="text/javascript">
document.addEventListener('alpine:init', () => {
Alpine.data('app', () => ({
input: '',
data: {},
error: false,
isLoading: false,
handleFetch() {
this.isLoading = true;
const requestId = this.input || '1';
fetch(`https://jsonplaceholder.typicode.com/todos/${requestId}`)
.then(response => {
if (! response.ok) {
this.error = true;
}
return response.json();
})
.then(json => {
this.isLoading = false;
this.data = json;
})
.catch(reason => {
this.error = true;
});
}
}));
});
</script>


