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

6/7/17

Staring With Vue.js - Part 2 (Components)

It is well known fact that it better to have your frontend code splitter into incapsulated parts - the components. Almost all js frameworks are implementing webcomponents in some way. Vue.js is not an exception.

Creating Component

When we created list of first 5 popular books we used for each book representation few html elements:


 <div class="row">
    <div class="col-xs-4 text-center"  v-for="book in books">
      <a href="#" class="thumbnail">
        <img v-bind:src="book.img" width="200" height="276" >
        <span>{{ book.title }}</span>
      </a>
    </div>
  </div>  

Instead of having all those html elements with classes styles and attributes we can have only one component element

Book Item


In Vue you can easily create component in following way
Vue.component('book-item', {
  props: ['book'],//<--property
  template: `
  <div class="col-xs-4 text-center">
      <a href="#" class="thumbnail">
        <img v-bind:src="book.img" style="height:226px" >
        <span>{{ book.title }}</span>
      </a>
  <div>
  `
}); 

Notice that this component has binding property "book" from which it gets a book object - the book the component should display
Finally we can use our book-item component inside book repeater:

  <div class="row">
    <book-item :book="b" v-for="b in books"></book-item>
  </div>  

for viewing code, please look at this jsfiddle

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...