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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With