v-for

up:: Vue Directives This loops through arrays and objects.

<ul>
	<li v-for="goal in goals">{{ goal }}</li>
</ul>

Warning

key is required when looping through Vue Components.

Getting the index

 <ul>
	<li v-for="(goal, index) in goals">{{ goal }}, index: {{ index }}</li>
</ul>

Looping through objects

 <ul>
	<li v-for="(value, key) in object">{{ value }}, key: {{ key }}</li>
</ul>

(you can also get the index from an object but it is rarely needed)

Looping through numbers

 <ul>
	<li v-for="num in 10">{{ num }}</li>
</ul>

Removing list items

 <ul>
	<li v-for="(goal, index) in goals" @click="removeItem(index)">{{ goal }}</li>
</ul>

We are passing the index to a function defined in our Vue Methods whenever an item is clicked (using v-on).

When removing an element, Vue moves the dynamic content around.

  1. You have a list with two elements.
  2. Remove the first one.
  3. Vue moves the second into the first one.

This can introduce some bugs.

Best practice

Hence, it is a good idea to add a unique key.

<li v-for="(goal, index) in goals" :key="goal">{{ goal }}</li>