Reputation: 7153
How would I create a v-for loop in Vue with the image array name being created as a string template?
So let's say I have 5 arrays of bedroom images coming back from the api with specific key names:
data() {
return {
Bedrooms: 5,
// values set in created(){}
Bedroom1Images: [],
Bedroom2Images: [],
Bedroom3Images: [],
Bedroom4Images: [],
Bedroom5Images: [],
}
}
And I want to loop each image in each array, but also, loop the whole thing so I only have one "bedroom-wrap" element in the template that gets printed in a loop.
Something like this, though this syntax doesn't work.
<div v-for="(n, index) in Bedrooms" :key="index"> // master outside loop
<div class="bedroom-wrap">
<label>Bedroom {{ n }}:</label>
<ul class="photos">
<li v-for="(item, index) in `Bedroom${n}Images`" :key="index"> // name array using `n` from outside loop?
<a data-fancybox="bedrooms" :href="item.thumbnails.full.url">
<img :src="item.thumbnails.large.url" alt="Bedroom Image" />
</a>
</li>
</ul>
</div>
</div>
Upvotes: 0
Views: 3145
Reputation: 6058
if you wrap the arrays into and an object then you can work as we want.
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
<div id='app'>
<div v-for="(n, index) in Bedrooms" :key="index"> // master outside loop
<div class="bedroom-wrap">
<label>Bedroom {{ n }}:</label>
<ul class="photos">
<li v-for="(item, index) in Images[`Bedroom${n}Images`]" :key="index"> {{item}}
</li>
</ul>
</div>
</div>
</div>
JavaScript:
new Vue({
el: '#app',
data() {
return {
Bedrooms: 5,
// values set in created(){}
Images: {
Bedroom1Images: [1, 2],
Bedroom2Images: [1, 2],
Bedroom3Images: [],
Bedroom4Images: [1, 2],
Bedroom5Images: [],
}
}
}
})
A working example of you code is here
Upvotes: 0
Reputation: 214957
The easiest is to put your images in a separate object:
data() {
return {
Bedrooms: 5,
// values set in created(){}
BedroomImages: {
1: [],
2: [],
3: [],
4: [],
5: [],
}
}
}
And then in your template you can do BedroomImages[n]
:
<div v-for="(n, index) in Bedrooms" :key="index"> // master outside loop
<div class="bedroom-wrap">
<label>Bedroom {{ n }}:</label>
<ul class="photos">
<li v-for="(item, index) in BedroomImages[n]" :key="index"> // name array using `n` from outside loop?
<a data-fancybox="bedrooms" :href="item.thumbnails.full.url">
<img :src="item.thumbnails.large.url" alt="Bedroom Image" />
</a>
</li>
</ul>
</div>
</div>
Upvotes: 1