How to load a component from a variable name in Vue.js?

Viewed 13862

I want to load a component from a dynamic variable name in my vue.js application.

I have the following component registered:

<template id="goal">
  <h1>Goal:{{data.text}}</h1>
</template>

Instead of loading it like this

<goal></goal>

I want to load from a variable name, something like this:

<{{mytemplate.type}}></{{mytemplate.type}}>

Where, of course, mytemplate.type would be, in this case equal to "goal"

4 Answers

I was having the same issue and because I was using Vue 3. After some research, I found out that the procedure to define dynamic components (async components) is a little different in Vue 3. I hope this code helps someone.

<template>
    <component :is="comp"></component>
</template>

<script>
//Vue 3 is having a special function to define these async functions
import {defineAsyncComponent} from "vue";

export default {
 name: "DynamicComponent",
 //I am passing the name of the Component as a prop
 props: {
     componentName:{
         type: String,
         required: true
     }
 },
 computed: {
  comp () {
      return defineAsyncComponent(() => import(`../components/${this.componentName}.vue`))
  }
}
}
</script>

I have no reason to doubt the answer @Rakshit provided was valid, but for my case, I didn't need so much complexity. Figured I'd share if anyone was in the same boat--wanted to reference a different component for each v-tab in vuetify3, this code was sufficient:

  <v-toolbar color="info-light">
    <v-tabs v-model="tab">
      <v-tab v-for="item in items" :key="item" :value="item">
        {{ item.name }}
      </v-tab>
    </v-tabs>
    <v-spacer></v-spacer>
  </v-toolbar>
  <v-window v-model="tab" fill-height>
    <v-window-item v-for="item in items" :key="item" :value="item">
      <component :is="item.component"></component>
    </v-window-item>
  </v-window>

And in the script section:

import ThatModule from "./ThatModule.vue";

export default {
  name: "CategorizeModule",

  data: () => ({
    tab: null,
    items: [
      {
        name: "Spending",
        component: <ThatModule></ThatModule>,
      },
Related