Vue.js Loop Statements
Loops use the v-for directive.
The v-for directive requires a special syntax in the form of site in sites, where sites is the source data array and site is the alias for the array element being iterated.
v-for can bind data to an array to render a list:
v-for Directive
<div id="app">
<ol>
<li v-for="site in sites">
{{ site.name }}
</li>
</ol>
</div>
<script>
new Vue({
el: '#app',
data: {
sites: [
{ name: 'tutorialpro' },
{ name: 'Google' },
{ name: 'Taobao' }
]
}
})
</script>
Using v-for in a template:
v-for
<ul>
<template v-for="site in sites">
<li>{{ site.name }}</li>
<li>--------------</li>
</template>
</ul>
v-for Iterating Over Objects
v-for can iterate over an object's properties:
v-for
<div id="app">
<ul>
<li v-for="value in object">
{{ value }}
</li>
</ul>
</div>
<script>
new Vue({
el: '#app',
data: {
object: {
name: 'tutorialpro.org',
url: 'http://www.tutorialpro.org',
slogan: 'Learning is not just about technology, it's about dreams!'
}
}
})
</script>
You can also provide a second parameter for the key:
v-for
<div id="app">
<ul>
<li v-for="(value, key) in object">
{{ key }} : {{ value }}
</li>
</ul>
</div>
A third parameter for the index:
v-for
<div id="app">
<ul>
<li v-for="(value, key, index) in object">
{{ index }}. {{ key }} : {{ value }}
</li>
</ul>
</div>
v-for Iterating Over Integers
v-for can also loop over integers:
v-for
<div id="app">
<ul>
<li v-for="n in 10">
{{ n }}
</li>
</ul>
</div>