Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register child component dynamically in Vuejs

Tags:

vue.js

vuejs2

I have a component, let's call it Parent.vue(code shown below). It uses the <component> tag provided by Vuejs to dynamically render a component.

It takes a prop named child which describes the type of the child component and the props it will take.

Now, the problem is that even if my Parent.vue renders only 1 child component at a time, it has to register all the 3 components, using the components object.

So, my question is: Is there a way to dynamically import and register these child components based on the type of the child? Something like a function that checks the child.type field and creates the components object with just the child that is required.

Any help would be appreciated

<template>
  <div>
    <component 
      :is="getComponentName(child.type)" 
      v-bind="child.props"
    >
    </component>
  </div>
</template>

<script>
  import Button from './Button.vue'
  import InputText from './InputText.vue'
  import DataTable from './DataTable.vue'

  export default{
    props:{
      child: Object
    },
    components:{
      Button,
      InputText,
      DataTable
    },
    methods:{
      getComponentName(type){
        switch(type){
          case 'button': return 'Button'
          case 'input-text': return 'InputText'
          case 'table': return DataTable
        }
      }
    }
  }
</script>

like image 366
Ankit Kante Avatar asked Jun 05 '26 18:06

Ankit Kante


1 Answers

Since the is property of component component can accept ComponentDefinition (See more about information here). So you can set it to the factory function which return dynamic import function.

    <template>
      <div>
        <button @click='name = "Apple"'>Apple</button>
        <button @click='name = "Banana"'>Banana</button>
        <component :is='component'/>
      </div>
    </template>
    
    <script>
      export default {
        data: () => ({
          name: 'Apple'
        }),
    
        computed: {
          component () {
            let name = this.name
            return () => import(`@/components/${name}`)
          }
        }
      }
    </script>

With this way your component will be load and execute when you use it without explicit register.

like image 141
User 28 Avatar answered Jun 07 '26 10:06

User 28