Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue JS loop with different components

Tags:

vue.js

vuejs2

I am using Vue JS to make a list that has one generic list item component. If there exists a none generic component that meets the correct type a custom component will be used.

 <email-queue-item v-for="item in queue"
                          :key="item.id"
                          :item="item"
                          v-if="type == 'EmailMessage'"></email-queue-item>
        <queue-item v-for="item in queue"
                          :key="item.id"
                          :item="item"
                          v-else></queue-item>

The code above better illustrates what I am trying to do. The problem I seem to have is due loops first creating two list and then checks the conditional. Is there a way in due to pick the right component vase on the type and then loop through the list?

The data Used to display these components is like this:

{
    name: Email,
    type: EmailMessage,
    data:[
        {...},
        {...},
        ...
    ]
}
like image 350
John Doe Avatar asked May 18 '18 20:05

John Doe


People also ask

How do I switch between Vue components?

Each component can be linked by using props to pass the methods which will switch the components on triggering a certain event. Here is an example: HTML. CSS.

Can you have multiple templates in Vue?

If you need a different template (or as many as you want) you just need to create another component that extends the Base Component.

How do I make reusable components Vue?

Each component you create in your Vue app should be registered so Vue knows where to locate its implementation when it is encountered in a template. To register your component in another component, you should add it to the components property in the Vue object.


1 Answers

Dynamic components make this pretty easy in the template:

<component
    :is="type == 'EmailMessage' ? 'email-queue-item' : 'queue-item'"
    v-for="item in queue"
    :key="item.id"
    :item="item"
/>
like image 184
Stephen Thomas Avatar answered Oct 08 '22 00:10

Stephen Thomas