I recently discovered that you can destructure in a v-for.
It turns out not many of you knew this either, as this ended up being one of my most popular tweets:
The reason this works is that Vue lifts the entire first portion of the v-for
straight into the argument section of a function:
<li v-for="____ in array"></li>
function (____) {//...}
This function is then used internally by Vue in order to render the list.
What this means is that any valid Javascript that you can put inside of a functions brackets can be put inside of your v-for
as well. You can set defaults or re-assign values if you want to:
<li v-for="{// Set a defaultradius = 20,// Destructure nested objectspoint: { x, y },} in circles">
Any sort of wild destructuring you like can be done here. Just don't go too crazy 😉
It's more widely known that you can grab the index out of the v-for
by using a tuple like this:
<li v-for="(movie, index) in ['Lion King','Frozen','The Princess Bride']">{{ index + 1 }} - {{ movie }}</li>
When using an object you can also grab the key:
<li v-for="(value, key) in {name: 'Lion King',released: 2019,director: 'Jon Favreau',}">{{ key }}: {{ value }}</li>
It's also possible to combine these two methods, grabbing the key as well as the index of the property:
<li v-for="(value, key, index) in {name: 'Lion King',released: 2019,director: 'Jon Favreau',}">#{{ index + 1 }}. {{ key }}: {{ value }}</li>
Vue does support iterating over Map
and Set
objects, but since they aren't reactive in Vue 2.x, their usefulness is quite limited. You can also use any Iterable here, including generators (which have some good use cases.)
As an aside, I have sometimes used a Map
or Set
, but typically only as an intermediate object to do a calculation. For example, if I need to find all unique strings in a list, I might do this:
computed() {uniqueItems() {// Create a Set from an array, which removes all duplicatesconst unique = new Set(this.items);// Convert that Set back into an array that we can use with Vuereturn Array.from(unique);}}
I have one last thing about v-for
that I want to share with you.
Did you know that you can also iterate over a string with v-for
?
This isn't in the documentation, and I only found it because I was reading through the code to figure out how v-for
was implemented, but here it is:
<p v-for="character in 'Hello, World'">{{ character }}</p>
This will print out each character inside of it's own p
element.
I'm not entirely sure where you would use this, but there it is 🤷♂️