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

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"



Solution 1:[1]

Use a dynamic component like this:

<component :is="myTemplate.type"></component>

Solution 2:[2]

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>

Solution 3:[3]

Answer from Rakshit Arora above works, but only with './' and '../' in import.

As for now (2022), '@' symbol is not allowed in import (https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations).

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Rakshit Arora
Solution 3 serebr
Solution 4 månebjælke