I am fairly new to Nuxt and Vuejs. I have been stuck on this for a few days now and have already googled for a solution but haven’t found any..
I have a page with component <VTextField></VTextField>
and <VSwitch></VSwitch>
, sample code of the page is as below
<script setup lang="ts">
import { ref } from 'vue';
</script>
<template>
<VTextField></VTextField>
<VSwitch></VSwitch>
</template>
But instead of directly using the component, I have a requirement that needs to be followed where I have an API that will provide me with the “type” and based on the “type” value will display the component.
I tried creating a function for this and the code is as below.
utils/RenderComponent.ts
import { defineComponent } from 'vue';
import { VTextField } from 'vuetify/components';
import { VSwitch } from 'vuetify/components';
export function renderComponent(type: any) {
switch (type) {
case 'Text':
return defineComponent({
components: { VTextField },
template: '<VTextField/>'
});
case 'switch':
return defineComponent({
components: { VSwitch },
template: '<VSwitch/>'
});
default:
throw new Error('Invalid component type');
}
}
Page.vue
<script setup lang="ts">
import { ref } from 'vue';
import { renderComponent } from '~/utils/RenderComponent';
</script>
<template>
<component :is="renderComponent('Text')" />
<component :is="renderComponent('Switch')" />
</template>
But the code does not work. I hope somebody can help and thank you in advance!