简体   繁体   中英

Use <component> 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'

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,
    };
  },
}

You should be able to use async components , loaded dynamically.

For example...

<component :is="p2Replacement"></component>
data () {
  return {
    p2Replacement: null
  }
},
methods: {
  setP2Replacement(component) {
    this.p2Replacement = () => import(`path/to/${component}.vue`)
  }
}

And call it like setP2Replacement('C1') or setP2Replacement('C3') .

The fixed parts in the import expression are required so Webpack can include the appropriate files using a glob pattern. See https://webpack.js.org/guides/dependency-management/#require-context

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM