Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 635
sigmaxf Avatar asked Jul 09 '17 16:07

sigmaxf


People also ask

How do I import a component into Vue JS?

STEP 01: First, Import the Child Component into the Parent Component inside script tag but above export default function declaration. STEP 02: Then, Register the Child Component inside the Parent Component by adding it to components object. STEP 03: Finally, Use the Child Component in the Parent Component Template.

How do I register a component in VUE JS?

When we want to globally register a component in Vue, we need to do it in this file. All you have to do is import your component, as you usually would, and then register it using app. component . import { createApp } from 'vue' import App from './App.

How do I name my Vue components?

Component names should always be multi-word, except for root App components, and built-in components provided by Vue, such as <transition> or <component> . This prevents conflicts with existing and future HTML elements, since all HTML elements are a single word.

How do I transfer data from components to Vue?

Using Props To Share Data From Parent To Child # VueJS props are the simplest way to share data between components. Props are custom attributes that we can give to a component. Then, in our template, we can give those attributes values and — BAM — we're passing data from a parent to a child component!


2 Answers

Use a dynamic component like this:

<component :is="myTemplate.type"></component>
like image 60
thanksd Avatar answered Oct 12 '22 05:10

thanksd


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>
like image 44
Rakshit Arora Avatar answered Oct 12 '22 06:10

Rakshit Arora