Is there a way to render a component dynamically in VueJS?

879 Views Asked by At

I have a component called CanvasComp which I am importing from my components folder. I am rendering this component on my template like <CanvasComp :jsoData="data"/>. It is sending the jsonData to the component. What I want is to render this component dynamically without having to display it manually on the template then pass the jsonData dynamically also.Below is my current implementation:

<template>
    <ion-page id="main-content">
        <CanvasComp :jsoData="data"/>
    </ion-page>
</template>

<script lang="ts">
    import { defineComponent, onBeforeMount, onMounted, ref, watch, watchEffect, reactive, computed  } from "vue";
    import { IonContent,IonPage } from "@ionic/vue";
    import CanvasComp from "@/components/CanvasComp.vue";

    export default defineComponent({
        name: "GraphView",
        components: {
        IonContent,
        IonPage,
        CanvasComp,
    },

    setup() {
        const data= [
            { id: 1, name: 'Default' },
            { id: 2, name: 'Demographics'},
            { id: 3, name: 'Other'},
        ];
    }

    return { data, CanvasComp }
</script>

Is there a way I can render that <CanvasComp :jsoData="data"/> in my template dynamically while passing the jsonData as well? e.g const CanvasComp = prop{jsonData: data}; then return it.

1

There are 1 best solutions below

0
DVN-Anakin On

Not sure if this is what you need, however there is a way how to dynamically render a component into the template:

Lets say we have a simple component components/HelloWorld.vue which accepts a text prop and renders it in an <h1> element:

<template>
  <h1>{{ text }}</h1>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      required: true,
    },
  },
};
</script>

Now I have another component components/Wrapper.vue which uses the <component> element to render a dynamic component based on the value of the dynamicComponent data property.

<template>
  <component :is="dynamicComponent" :text="dynamicText" />
</template>

<script>
import { defineComponent, markRaw } from 'vue';
import HelloWorld from './HelloWorld.vue';

export default defineComponent({
  data() {
    return {
      dynamicComponent: markRaw(HelloWorld),
      dynamicText: 'Hello people!',
    };
  },
});
</script>

In the example above the dynamicComponent data property is a function that returns the imported HelloWorld component, and the dynamicText data property is a string with the value "Hello people!". This value will be passed as the text prop to the HelloWorld component when it's rendered.

Here is a link to a working DEMO.

In your case I imagine you could dynamically render the CanvasComp component the same way I have rendered my HelloWorld component. And of course, instead of the text prop you would use the jsoData prop.