I’m creating a bookstore app with Vue.js. The books are in this API https://api.myjson.com/bins/1h3vb3, but I can’t show them in my HTML with the following function and I don’t understand why:
<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!"); }); } } });
Advertisement
Answer
axios.get
resolves to a Response
, which stores the received data in the data
property. In your code, you’ve incorrectly set this.books
to response
, which is the entire Response
object. You should instead reference response.data.books
:
axios.get(...).then(response => this.books = response.data.books)
Also, to render a list of items, use v-for="book in books"
like this:
<div v-for="book in books"> <div>Details: <strong>{{ book.detalle }}</strong></div> <div>Title: <strong>{{ book.titulo }}</strong></div> <div>Description: <strong >{{ book.descripcion }}</strong></div> <div>Language: <strong>{{ book.idioma }}</strong></div> </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.data.books; }) .catch(e => { console.log("No found!"); }); } } })
.book { margin: 1rem; }
<script src="https://unpkg.com/vue@2.6.11/dist/vue.min.js"></script> <script src="https://unpkg.com/axios@0.19.2/dist/axios.min.js"></script> <div id="vue-app"> <button @click="getAPI">Get data from API</button> <div id="list-books" class="book" v-if="books" v-for="book in books"> <!-- <div>Cover page: <strong>{{ books }}</strong></div> --> <div>Details: <strong>{{ book.detalle }}</strong></div> <div>Title: <strong>{{book.titulo}}</strong></div> <div>Description: <strong >{{book.descripcion}}</strong></div> <div>Language: <strong>{{book.idioma}}</strong></div> </div> <div class="text-center" v-else> No results! </div> </div>