Vue.js quick tip: Using destructuring assignment in for loops
Vue.js is a modern, lightweight frontend framework which massively gained popularity over the past few years. If you have never heard about Vue.js before and are interested in learning more about it, the best way to get started is to read through the official guide.
Vue.js provides a v-for
directive, which can be used for displaying a list of items using the data from an array.
The following example renders a list of products with it's name and price.
var app = new Vue({
el: '#app',
data: {
products: [
{ name: 'Product 1', price: 300 },
{ name: 'Product 2', price: 100 },
{ name: 'Product 3', price: 200 }
]
}
});
<ul>
<li v-for="product in products">{{ product.name }} - {{ product.price }}</li>
</ul>
This is pretty straight forward and the way you would usually want to render a list.
There is really nothing wrong with the above code, but there is a small aspect, which really bugs me. As you can see, we are repeating the product
identifier inside the output twice ({{ product.name }}
and {{ product.price }}
).
We are modern web developers (at least I hope so) and therefore we are going to use modern ES6 functionality (ignoring the fact, that old browsers, which almost nobody uses, don't support those features - namely IE).
The feature we are going to use is called destructuring assignment. Basically, what the destructuring assignment allows us to do, is to pull a specific property off of an object and store it in a variable.
Now, rewriting the above code with the destructuring assignment, we can refactor the rendering part to the following:
<ul>
<li v-for="{name, price} in products">{{ name }} - {{ price }}</li>
</ul>
So you might wonder: What does the above code now do differently than before? Well, the output will still be the same, but in my opinion this approach is way more readable and easier to understand. The above code pulls off the properties named name
and price
from each element inside the products array and stores them in variables named name
and price
. That way, inside the for loop you can use the variables name
and price
instead of referencing them with product.name
and product.price
each time.
This might not seem too useful in the above, short example. But imagine you have a much longer handler inside the for loop, in which you need to reference multiple properties multiple times. In that case, you might save a few key strokes, as you don't have to reference them with the product
identifier each time.