List Rendering


Different types of data

The "data" object in the Vue instance is nothing but a javascript object. Meaning that you can specify all kinds of elements in it: Strings, integers and even arrays. 

In real-world applications, you probably do a lot of ajax calls and in most cases you receive arrays as the response. 

So lets review another Vue directive called "v-for" which is used for rendering lists. 


Repeating HTML Elements (v-for)

Vue can loop through arrays and repeat HTML elements for you. Just use the "v-for" directive on any HTML element that you intend to repeat. 

Let's create a Vue instance including an array in its data:

new Vue({
el: '#app',
data: {
fruits: [
'apple', 'orange', 'banana', 'watermelon'
]
}
})

And loop through the fruits array to repeat a HTML element:

<ul>
<li v-for="item in fruits">{{ item }}</li>
</ul>

Result:

  • apple
  • orange
  • banana
  • watermelon

v-for also supports an optional second argument for the index of the current item:

<ul>
<li v-for="(item, index) in fruits">{{ item + ' - ' + index }}</li>
</ul>

Result:

  • apple - 0
  • orange - 1
  • banana - 2
  • watermelon - 3

Inside v-for blocks we have full access to parent scope properties. For example we could do fruits.length to get the count of array.

v-for can be done on any HTML element. This even includes our own created HTML elements which are called components (which we will review in future chapters). 


Range v-for

v-for can also take an integer to repeat the HTML element n times:

<ul>
<li v-for="n in 5">{{ n }}</li>
</ul>

Result:

  • 1
  • 2
  • 3
  • 4
  • 5

Comments: