Vue.js Looping v-for and template

If you're just getting started with this series of Vue.js posts, you should start with the Vue.js Starter Page.

Vue.js offers some basic looping constructs with v-for that you can loop over data objects and even arrays of data.

First, the vue.js instance is loaded with some data.

Looping Over Lists


Looping over a regular array of a simple list.
  • {{beatle}}

Looping an array containing data objects.
  • {{musician.name}} - {{musician.instrument}}


Looping over an array without outputting the actual markup, use the <template> tag. Don't believe me? View Source.


Want to loop over an array containing data objects when you don't know the name of the key? Try this:


<!doctype html>

<html>
<head><meta charset="UTF-8"><title>VueJS</title>
<script src="https://unpkg.com/vue@2.3.0"></script>

</head>
<body>

<div id="app"> <h3>Looping Over Lists</h3> <!-- "beatle" represents the index of the loop and "beatles" is the actual array values --> <br> Looping over a regular array of a simple list.<br> <ul> <li v-for="beatle in beatles">{{beatle}}</li> </ul> <br> <!-- this loop is over an array of objects, so we need to clarify with a nested loop--> Looping an array containing data objects.<br> <ul> <li v-for="musician in rush"> {{musician.name}} - {{musician.instrument}} </li> </ul> <br><br> <!-- don't want to use li? You can output in a div, but what if you don't want THAT to output? Use the "template" tag, and that won't output at all --> Looping over an array without outputting the actual markup, use the <strong><template></strong> tag. Don't believe me? View Source.<br> <template v-for="(musician, index) in rush"> <h3>{{index}}. {{musician.name}}</h3> <p>{{musician.instrument}}</p> </template><br><br> Want to loop over an array containing data objects when you don't know the name of the key? Try this: <br> <template v-for="musician in rush"> <div v-for="val,key in musician"> {{key}}: {{val}} </div> </template> </div> </body> <script> var vm = new Vue({ el:'#app', data: { name: 'elvis', beatles: ['John', 'Paul', 'Ringo', 'George'], rush:[ {name:'Geddy', instrument:'vocals'}, {name:'Alex', instrument:'keyboards'}, {name:'Neil', instrument:'percussion'} ] } }); </script> </html>

Link your website to this page! Copy and paste the URL below:
http://www.cfsnap.com/vue-js/vue-js-looping-v-for-and-template/