Skip to content
Advertisement

Use that was imported in the parent

I’m building a component that manages other components. It dynamically render components in specific places depending on the props and inputs, much like an orchestrator.

Use case

My orchestrator have the following placeholders, like a grid (p1 … p6):

|-p1-|-p2-|-p3-|
|-p4-|-p5-|-p6-|

In a given moment, it renders the component C1 into p2 and C2 into p6:

|-p1-|-C1-|-p3-|
|-p4-|-p5-|-C2-|

In another moment, it replaces the C1 by C3:

|-p1-|-C3-|-p3-|
|-p4-|-p5-|-C2-|

The problem

Given this dynamism, I can’t (as far as I know) use slots. So I’m using component tags with the :is prop in order to dynamically render the correct component. The problem is that in order for the :is to work, I must have the component defined in my orchestrator/manager component. And I would like to keep it separated for reuse, doesn’t make sense to import the components there. One solution would be to globally register the components. I would like to avoid that if possible. Is there a way? I’m open to any kind of reflection-magic you may think n_n’

Advertisement

Answer

You can just pass the component via a prop like this:

Orchestrator.vue

<component :is="comp"/>
export default {
  props: ['comp']
}

Test.vue

<orchestrator :comp="MyComponent"/>
import Orchestrator from './orchestrator.vue'
import MyComponent from './my-component.vue'

export default {
  components: {
    Orchestrator,
  },

  data() {
    return {
      MyComponent,
    };
  },
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement