【问题标题】:Looping through an array using AlpineJS returns no results使用 AlpineJS 循环遍历数组不返回结果
【发布时间】:2021-12-31 02:21:20
【问题描述】:

我正在尝试使用 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>

【问题讨论】:

    标签: javascript arrays alpinejs


    【解决方案1】:

    您似乎对这个 API 返回的数据类型有错误的认识。将您传递给 fetch 函数的 URL 复制并粘贴到浏览器中。希望您很快就会看到此端点不返回数组,而是返回一个对象!

    function alpineInstance() {
      return {
        // we'll set our data to hold an object
        bookResponse: {}
      }
    }
    <html>
    
    <head>
      <script defer src="https://unpkg.com/alpinejs@3.x.x/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>

    【讨论】:

    • 非常感谢布伦丹!您的回答绝对正确,我非常感谢您的帮助。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多