javascript - 我在 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!");
});
}
}
});
解决方案
也许您还没有粘贴完整的代码,但是您已经声明了您的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/
推荐阅读
- cakephp - 在客户助手中使用 Acl 组件
- python - 从python子类中的属性中删除属性(getter/setter)
- mysql - 我的 SQL 中存在日期和日期时间比较问题
- user-interface - Pentaho Report Designer 的 UI 太小
- c# - 部署时Winform应用程序重新启动不起作用
- reactjs - 如何将 ant.design 跨度重置为默认值?
- javascript - 使用 p5.js 在 JavaScript 中未定义 JSON 属性
- java - 将 JButton 添加到 JPanel 到 JFrame
- c# - 在 DbUpdateConcurrencyExpcetion 上实现乐观并发
- python - 如何正确处理类的属性变化?