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"
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.
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.
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.
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!
Use a dynamic component like this:
<component :is="myTemplate.type"></component>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With