somascope
3/17/2018 - 12:29 AM

Vue v-for examples

The built-in v-for directive allows us to loop through items in an array or object.

v-for with Numbers
-----------------------
// Enumeration is 1-indexed, not 0-indexed
<li v-for="n in 10"></li>

// Adding several placeholder <p> elements, each with a unique key
<p v-for="n in 25" :key="`a-${n}`">Scroll down to close</p>

v-for with Arrays
-----------------------
// Basic
<li v-for="item in items"></li>

// Including an index (can be named anything)
<li v-for="(item, index) in items"></li>

// Recommended: use a keyed v-for
// Note: It's NOT ideal to use the index for the key
// Example 1 shows a property 'id' in the items
<li v-for="item in items" :key="item.id"></li>
// Example 2 for if you don't have a unique value other than a name'
<li v-for="item in items" :key="item.name"></li>
// Example 3 for if item is an object that has a '.key' property
<li v-for="item in items" :key="item['.key'"></li>

// Nesting v-fors
<li v-for="person in persons">
  <span v-for="item in person"> {{ item }}</span>
</li>

v-for with Objects
-----------------------
// Value & key
<li v-for="(value, key) in objectItems"></li>

// Value, key and index
<li v-for="(value, key, index) in objectItems">