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

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