Destructuring Variables in Vue.js Loops

— 2 minute read


The v-for attribute allows us to repeat a piece of markup for each item in an array. The example below shows a list being populated from an array of objects.

<ul>
<li v-for="item in items" :key="item.id">
:
</li>
</ul>

To show the name and id properties of the item object we use the familiar item.id and item.name syntax. If we were handling this object in plain JavaScript code we might destructure the object into variables:

const { id, name } = item;

We can do exactly the same thing within Vue.js v-for loops so we can omit the item. part. This is useful when dealing with a small number of properties but might become a bit unwieldy if you're dealing with tons of properties.

Notice we can also use the id in the :key attribute using the destructured variable.

<ul>
<li v-for="{ id, name } in items" :key="id">
:
</li>
</ul>

Sometimes we want to access the index of the item within the array and we can still do that even when destructuring:

<ul>
<li v-for="({ id, name }, index) in items" :key="id">
# - :
</li>
</ul>

Filed under