6/25/17

Loading Data From Api Vue - Part 3 (fetch)

In previous post we created the "Book Club" app home page which displays list of most popular books.
Of course all books came currently from static variable.
Now instead of display static data lets try to display data from api.

Fetch

Changes are very slight: In the "data" section we need to define books as empty array instead of static data:


new Vue({
  el: '#app',
  data: {
    title: 'Pnei Kedem Book Club',
    books: [] //<--empty
  }
})

Next step is to add "get" call to API inside "mounted" method:

new Vue({
  el: '#app',
  data: {
    title: 'Pnei Kedem Book Club',
    books: []
  },
  mounted() {
    fetch("//api.mlab.com/api/1/databases/mydb/collections/books?apiKey=myKey")
    .then(response =>response.json())
    .then(response => {
        this.books = response;
     })
   }
})

As you can see - the change is very slight...(no services, no dependency injections needed)
For running code see this jsfiddle

No comments:

Post a Comment

Getting started with docker

It is very simple to get started usig docker. All you need to do-is download the docker desktop for your system Once you get docker syste...