Qwertie
Qwertie

Reputation: 6483

Adding vue components based on condition in v-for

I have a JS array formatted similar to

[{type:'text', data: 'some text'},{type: 'image',  data: 'link/to/image'}]

for the different values of type I have different vue components (<text-block>, <image-block>) and I want to use a v-for to loop over this array and based on the type, create the right vue component.

The examples for v-for show creating the same element many times like many <li>. Is there a way I can create different elements in a v-for?

Upvotes: 2

Views: 2193

Answers (2)

Rohan Shukla
Rohan Shukla

Reputation: 89

You can do something like this, say there's list of movies in an array:

<div id="app">
<ul>
<li v-for="movie in movies">{{ movie }}</li>
</ul>
</div>
<script>

var app = new Vue({

el: '#app',
data: {
  movie: ['some movie 1', 'movie 2', 'idk movies man']
}

});

setTimeout(function() {
app.movies.push('random movie');

}, 2000);

</script>

Upvotes: -1

Axel
Axel

Reputation: 5111

You can just use v-if:

<div v-for="(loop, index) in loops" :key="index">
    <text-block v-if="loop.type === 'text'"></text-block>
    <image-block v-if="loop.type === 'image'"></image-block>
</div>

You can also use dynamic components:

<div v-for="(loop, index) in loops" :key="index">
    <component :is="loop.type + '-block'"></component>
</div>

Make sure you have imported the components and defined them on the instance.

Upvotes: 2

Related Questions