首页 > 解决方案 > 我在 Vue.js 中使用 axios 的 API 出现问题

问题描述

我正在使用 Vue.js 创建一个书店应用程序。这些书在此 API https://api.myjson.com/bins/1h3vb3中,但我无法使用以下函数在我的 HTML 中显示它们,我不明白为什么:

<div id="list-books" v-if="books && books.length">
  <div>Cover page: <strong>{{ books }}</strong></div>
  <div>Details: <strong>{{ books.detalle }}</strong></div>
  <div>Title: <strong>{{books.titulo}}</strong></div>
  <div>Description: <strong >{{books.descripcion}}</strong></div>
  <div>Language: <strong>{{books.idioma}}</strong></div>
</div>
<div class="text-center" v-else> No results! </div>
new Vue({
  el: "#vue-app",
  data() {
    return {
      title: "Ubiqum Bookstore",
      books: []
    };
  },
  methods: {
    getAPI() {
      axios
        .get("https://api.myjson.com/bins/1h3vb3")
        .then(response => {
          this.books = response;
        })
        .catch(e => {
          console.log("No found!");
        });
    }
  }
});

标签: javascriptvue.js

解决方案


也许您还没有粘贴完整的代码,但是您已经声明了您的getAPI方法,但我看不到您实际运行它的位置。

我缺少的是这样的:

...
data() {
  return {
    title: "Ubiqum Bookstore",
    books: []
  };
},
mounted() {
  this.getAPI();
},
methods: {
  getAPI() {
    ...
  }
}

编辑见下面的代码片段。您还犯了一些错误:

  • 您的 books 数组显示为空,因为this.books = response;将整个响应对象分配给它。实际数据更深一些,因此this.books = response.data.books;.
  • 你错过了一个v-for循环你的结果
<div class="book" v-for="book in books">`
...
</div>

工作jsfiddle: https ://jsfiddle.net/6bytes/ufbaem0j/8/


推荐阅读