Vue: Allow components to be called dynamically based on condition

Created on 16 Apr 2020  ·  2Comments  ·  Source: vuejs/vue

What problem does this feature solve?

It allows the developer to control what to render without having to use a bunch of if-else statement and also allows us to call the component from outside of the scope.

What does the proposed API look like?

Suppose I'm creating a package/module that takes the data from the outside. And based on the data, it can call let's say different components.

Component A // takes 2 props. (propA,propB)
Component B // takes 3 props (propA,propB,propC)
Component C // takes 1 prop (propD)

In my parent component,

I would call

// SomeParentComponent.vue that accepts "items (array)" as props

<template>
    <div>
       <div v-for="item in items">
            <div v-render-component="item.componentName" v-component-props="item.props" /> // item.props = { propA: value, propB: value ... }
       </div> // props are being passed down, sort of like vue router's params and query props.
    <div>
</template>

Suppose we have 3 different Card Components with unique and some similar functionalities. We are rendering a single item and based on the condition we are calling the component.

But with the current API, we might need to do something like

... 
// inside the loop
<div v-if="item.componentName ==== 'ComponentA'" />
    <ComponentA :propA="item.propA" ... />
</div>

<div v-if="item.componentName ==== 'ComponentB'" />
    <ComponentB :propA="item.propA" ... />
</div>

<div v-if="item.componentName ==== 'ComponentC'" />
    <ComponentC :propA="item.propA" ... />
</div>
...

Also, in the SomeParentComponent, there is no way to call on different components for another purpose. If we think of maybe a table, the data is different but we would be able to use the same component (SomeParentComponent) etc.
Example

//Users.vue 

<SomeParentComponent :items="users" />

// Orders.vue

<SomeParentComponent :items="orders" />

This way, not only the template portion remains the same but also the logical portion of a component. Thus, letting us comprehend the idea of 'component', a component handles a responsibility.

We can have vue directives for "v-render-component" and "v-component-props" and obviously these are pseudo names.

Most helpful comment

<component :is="item.componentName" v-bind="item.props">

All 2 comments

<component :is="item.componentName" v-bind="item.props">

You can already do this as @jacekkarczmarczyk showed you


Remember you can use the forum or the Discord chat to ask quick questions!

Was this page helpful?
0 / 5 - 0 ratings