Destructuring v-for loops in Vue.js

October 15, 2020

Vue.js provides a useful directive for looping over lists called v-for.

It is simple to use too, we just need some data to loop over:

export default {
  data() {
    return {
      pizzas: [
        {
          id: 1,
          name: "Margherita",
          price: 7.95
        },
        {
          id: 2,
          name: "Pepperoni",
          price: 8.95

        },
        {
          id: 3,
          name: "Vegetarian",
          price: 8.95
        },
      ],
    }
  }
}

Now we can use the v-for directive to loop over our pizzas in the HTML template:

<ul>
  <li v-for="pizza in pizzas" :key="pizza.id">
    <span>{{ pizza.id }}</span> ~ 
    <span>{{ pizza.name }}</span> ~
    <span>{{ pizza.price }}</span>
  </li>
</ul>

And we would see this result in the browser:

1 ~ Margherita ~ 7.95

2 ~ Pepperoni ~ 8.95

3 ~ Vegetarian ~ 8.95

This all works fine, but we can also make use of array destructuring to unpack the values of each pizza, and place them into variables:

<ul>
  <li v-for="{ id, name, price } in pizzas" :key="id">
    <span>{{ id }}</span> ~ <span>{{ name }}</span> ~
    <span>{{ price }}</span>
  </li>
</ul>

This gives us 3 variables we can directly use: id, name and price. These can be accessed in our template, and also in our key attribute too, without needing to use the pizza object prefix (ie pizza.name).