List Indexes & Keys
A little HTML, CSS, & JavaScript knowledge if recommended for this course.
To follow along, the starter folder is located in The Vue instance lesson.
Updating posts
Currently, we are not making any changes to any of our list's, so Vue does not have much work to do.
However, in real world apps our data may often change. Either from the user adding something into a form, or an update from our server. And maybe even a new blog post being added and updated with an API.
Once Vue receives these updates, since we used the data property it will update the HTML with the new values. This happens because data properties are reactive.
This is simple enough for something such as a string of text, but what if we had thousands of blog posts? Imagine we deleted or updated one right in the middle. How does Vue deal with this?
The key attribute
The answer is to use a special attribute called a key:
<!-- index.html -->
<article v-for="post in posts" key="">
A key is a way to add a unique identifier to each one of our list items. If we had hundreds or thousands of blog posts, having this unique key will allow Vue to better identify each element when the time comes to update or re-order. If we never had keys, Vue would need to refer back to an algorithm to detect these changes.
This key should be unique such as a product id. For our blog we have a unique id for each post, meaning we can use post.id:
<article v-for="post in posts" key="post.id">
If we just add attributes like this, the value we pass in will be read as a string, such as "post.id", rather than the value of the variable.
The v-bind directive
When we need to use dynamic values for attributes such as a variable, or even JavaScript, we can use v-bind:
<article v-for="post in posts" v-bind:key="post.id">
Or, the simpler shorthand of the colon:
<article v-for="post in posts" :key="post.id">
Just like v-for, this is a Vue directive. And now our key will be read as the id value such as 1,2,3, rather than a string of text.
Accessing the index position
Also when using v-for, we can access the index number. This is the position of each one of our items in the array, our first blog post is position zero, then 1, and so on:
<article v-for="(post, index) in posts" :key="post.id">
And we can access this index and display it just like we do with other data properties:
<article v-for="(post, index) in posts" :key="post.id">
  {{index}}
This can be useful for things such as numbering the items we display, but this is not required for our blog so we can remove.
It is recommended to not use this index value for a key, if no key is supplied, Vue will make use of the index anyway.
Along with binding a key, we can also bind other attributes such as class and style. And this is what we will cover in the next lesson.