我正在嘗試使用 AlpineJS 遍歷一個陣列,但在我的一生中,我無法獲得任何輸出。
我希望更熟悉 AlpineJS 的人能夠提供幫助。
提前致謝。
這是代碼:
<script>
function alpineInstance() {
return {
books: []
}
}
</script>
<div
x-data="alpineInstance()"
x-init="fetch('https://www.googleapis.com/books/v1/volumes?q=Alpine')
.then(response => response.json())
.then(data => books = data)">
<template x-for="(book, index) in books" :key="index">
<div x-text="book.items.volumeInfo.title"></div>
</template>
</div>
uj5u.com熱心網友回復:
看起來您對這個 API 回傳的資料型別有誤解。復制您傳遞給fetch函式的 URL并將其粘貼到瀏覽器中。希望您很快就會看到此端點不回傳陣列,而是回傳一個物件!
function alpineInstance() {
return {
// we'll set our data to hold an object
bookResponse: {}
}
}
<html>
<head>
<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
</head>
<body>
<div x-data="alpineInstance()" x-init="fetch('https://www.googleapis.com/books/v1/volumes?q=Alpine')
.then(response => response.json())
.then(data => bookResponse = data)">
<!-- instead of mapping over an object, which will throw an error, we'll map over bookResponse.items !-->
<template x-for="(item, index) in bookResponse.items" :key="index">
<div x-text="item.volumeInfo.title"></div>
</template>
</div>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/399723.html
標籤:javascript 数组 高山
上一篇:回傳HTTP請求資料
下一篇:使用jq決議陣列中的JSON元素
