icon-dark icon-light
Cover image for Key attribute in Vue

Key attribute in Vue

Vue does the heavy lifting of updating what’s rendered to the screen. But there’s only so much that Vue can know about your app and how it should do these updates.

Developer needs to give vue some hints for it to render. The key attribute tells Vue how your data relates to the HTML elements it’s rendering to the screen.

Please don’t mistake it to be a directive like v-for. It’s not even a prop, even though it looks exactly like one.

Let’s say you’re rendering a list of components using v-for, and those components have one or more of the following:

  • Their own local state
  • Some sort of initialization process, typically in created or mounted hooks
  • Non-reactive DOM manipulation, through jQuery or vanilla APIs

If you sort that list, or update it in any other way, you’ll need to re-render some of the components in that list. But you won’t want to re-render everything in the list, just the things that have changed.

This is where keys come in.

Avoid using an index as the key

Developers tend to make the key value as the index of the array. But it’s not helpful as its not tied to that specific object.

Let’s see an example.

Take a list of people (Array of objects)

const peopleList = [
  { name: 'Derek', age: 31 },
  { name: 'Tina', age: 23 },
  { name: 'Simon', age: 25 },

Lets render this list now

  <li v-for="(people, index) from peopleList" :key="index">
    {{ people.name }} - {{ people.index }}

The output for this would be:

Derek - 0
Tina - 1
Simon - 2

If we remove Tina, we will get this:

Derek - 0
Simon - 1

Derek stays with the same index of 0, so Derek is still using the same component after the change. Tina had the index of 1, but now Simon has that index. So Simon took over the component that Tina had, instead of sticking with his own component.

Now let’s try to keep the same component for Simon, even after deleting Tina’s component.

Unique ID as key

Let’s look at the updated list:

const peopleList = [
  { id: 'derek-31', name: 'Derek', age: 31 },
  { id: 'tina-23', name: 'Tina', age: 23 },
  { id: 'simon-25', name: 'Simon', age: 25 },

What have we done here now? We just gave every one a unique id in the list. Now let’s use this as the key’s value instead of using index as the value

  <li v-for="people from peopleList" :key="id">
    {{ people.name }} - {{ people.index }}

Now the output would be:

Derek - derek-31
Tina - tina-23
Simon - simon-25

If we remove Tina now, the output would be:

Derek - derek-31
Simon - simon-25

Initially in the previous example Vue didn’t know how to update the DOM, as it relied on key’s value as index. Now, Vue knows that it can keep the two components for Derek and Simon, and all it has to do is delete Tina’s component.

This is really useful, and helps us a lot when we have more complex components.

If you like this short article hit the 👍🏻❤️