I am new to the world of javascript and javascript-frameworks. What is the practical use of track-by
or key
in v-for
in Vue JS?
I read the documentation, but did not really understand its use.
Generally I would recommend you use a key
every single time that you are using v-for
. The main reason for this is because Vue, for performance reasons, tries to be smart and and re-use existing components when it re-renders. This can cause you to run into problems, especially with components, because components have an internal state. If the component is not paying attention to changes in it's properties then it will render with it's previous internal state and it will appear as if the displayed information was not updated properly.
Here is a prime example from a question I answered a few weeks ago. The fiddle shows iteration over a component without using a key.
<li v-for="item in items">
<test-component :prop1="item"></test-component>
</li>
Notice when you click the change data button that the property values (the first list) change, but the internal state of the component (the second list) does not change. This would typically mean you would not see an update or would see something that did not appear to update in the Vue.
By adding a key to the components, however, you are telling Vue that each component has a specific ID that and Vue will only re-use that component if it has the same ID. This prevents a lot of odd behavior that typically shows up. Here is that same fiddle updated.
<li v-for="item in items" :key="item">
<test-component :prop1="item"></test-component>
</li>
Now when you click the change data button you will notice that the internal state always matches the property.
This is literally one of the most common fixes to issues that pop up here on StackOverflow. Keys are not just useful for list rendering. Generally if you see something funny going on in Vue where a something does not appear to be updating the way you expect, using a key will fix the issue.
Here are a few relevant bits of information about key from the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With