32

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 4

50

Use a dynamic component like this:

<component :is="myTemplate.type"></component>
Sign up to request clarification or add additional context in comments.

Comments

19

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 has a special function to define these async functions
import {defineAsyncComponent} from "vue";

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

Comments

2

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).

2 Comments

This "answer" should be a comment.
His reputation isn't high enough to post comments yet.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.