How can I dynamically render a component using VueJS?

Incorporating a component named CanvasComp from my components folder, I am rendering it on the template like

<CanvasComp :jsoData="data"/>
to send jsonData to the component. However, I am seeking a way to dynamically render this component without manually displaying it on the template and pass the jsonData dynamically as well. Here 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>

Exploring if there is a method to dynamically render

<CanvasComp :jsoData="data"/>
in the template while passing the jsonData, for example like
const CanvasComp = prop{jsonData: data};
then returning it.

Answer №1

If you're unsure if this is the solution you're looking for, there is a method to dynamically display a component within a template:

Let's consider a basic component components/HelloWorld.vue which takes a text prop and shows it in an <h1> element:

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

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

Now, I also have another component components/Wrapper.vue that utilizes the <component> element to dynamically show a 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 given example, the dynamicComponent data property is a function that provides the imported HelloWorld component, and the dynamicText data property is a string with the content "Hello people!". This content will be passed as the text prop to the HelloWorld component when it gets displayed.

You can access a functional DEMO via this link.

In your scenario, you could potentially exhibit the CanvasComp component in the same manner as illustrated with my HelloWorld component. Instead of the text prop, you would employ the jsoData prop.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Regex to replace special characters in TypeScript

I need assistance in removing the characters "?" and "/" from my inner HTML string. Can you guide me on how to achieve this using regex? For example, I would like to replace "?" with a space in the following content. "Hello?How are you?<a href="http:/ ...

Retrieve the service variable in the routing file

How do I access the service variable in my routing file? I created a UserService with a variable named user and I need to use that variable in my routing file. Here is the approach I tried, but it didn't work: In the routing file, I attempted: cons ...

Unable to execute the Vite project

I ran into an issue with my Vite project yesterday. I closed it and now that I have reopened it, the 'npm run dev' command is throwing an error. My project is built using Vite with React and TypeScript. Attached is a screenshot of the error mess ...

Excessive repetition in the style of writing for a function

When it comes to TypeScript, a basic example of a function looks like this: let myAdd: (x: number, y: number) => number = function ( x: number, y: number ): number { return x + y; }; Why is there redundancy in this code? I'm having trouble g ...

Using Angular and Typescript to implement a switch case based on specific values

I am attempting to create a switch statement with two values. switch ({'a': val_a,'b': val_b}){ case ({'x','y'}): "some code here" break; } However, this approach is not functioning as expected. ...

How can I pass a DOM element as a prop in Vue 3?

As someone who is brand new to Vue, I'm exploring the possibilities. Although it's not something I typically do, I believe achieving a similar outcome in React + JSX (untested) could look like this: render() { const el = <p>Blah <a hre ...

Guide to implementing fullpagejs with Angular 7 selectors

I have been working on an Angular 7 project with fullpagejs by Alvarotrigo. Everything seems to be functioning properly, but I am facing an issue where the content of my website is not visible because the color of fullpagejs covers it all. When I use norma ...

Angular's HttpClient.get method seems to have trouble retrieving real-time data from a Firebase database

I have been debugging and I suspect that the error lies in this part of the code. The DataService class's cargarPersonas function returns an Observable object, but I am struggling to understand how to properly retrieve the database data and display it ...

Troubleshooting: Resolving the error message 'Unable to assign to Partial<this>' within a subclass method

If I call the base class's update method using a subclass instance, it functions as expected. However, I encounter an error when attempting to do so within a subclass method: Argument of type '{ prop: number; }' is not compatible with par ...

Troubleshooting Problem with Next.js 13 Integration, Supabase, and Server Actions in layout.tsx

I'm currently developing a Next.js 13 application and experimenting with managing user authentication through Supabase. I've encountered some challenges when attempting to verify if a user is logged in using an asynchronous function within my lay ...

Set every attribute inside a Typescript interface as non-mandatory

I have defined an interface within my software: interface Asset { id: string; internal_id: string; usage: number; } This interface is a component of another interface named Post: interface Post { asset: Asset; } In addition, there is an interfa ...

Encountered an unexpected error in Vue: "Maximum call stack size exceeded callWithAsyncErrorHandling - Uncaught Range

<button onClick="test">Test</button> Issue encountered in Vue 3 that caused significant troubleshooting: Error message: Uncaught RangeError: Maximum call stack size exceeded callWithAsyncErrorHandling @vue/cli 4.5.11 { "depen ...

Error message in TypeScript with Puppeteer library: "Element not found"

Incorporating puppeteer-core as a dependency in my TypeScript project within Visual Studio 2019 has caused an issue during the build process. The error message displayed is shown by a red squiggly line under Element: https://i.stack.imgur.com/HfJCu.png ...

Utilizing global enumerations within VueJS

Is there a way to effectively utilize global enums in Vue or declare them differently? My current setup is as follows: Within my types/auth.d.ts: export {}; declare global { enum MyEnum { some = "some", body = "body", o ...

Angular 13 does not currently have support for the experimental syntax 'importMeta' activated

Since upgrading to angular 13, I've encountered an issue while attempting to create a worker in the following manner: new Worker(new URL('../path/to/worker', import.meta.url), {type: 'module'}) This code works as expected with "ng ...

The element class type 'xxx' is lacking several properties compared to the 'ElementClass' type, including context, setState, forceUpdate, props, and others. This issue is flagged with error code TS2605

Encountering an error while attempting to execute my react app: D:/React/my-components/src/App.tsx TypeScript error in D:/React/my-components/src/App.tsx(23,4): JSX element type 'Confirm' is not a constructor function for JSX elements. ...

Best Practices for Converting TypeScript to JavaScript

What is the recommended approach to converting this JavaScript code into TypeScript? JAVASCRIPT: function MyClass() { var self = this, var1 = "abc", var2 = "xyz"; // Public self.method1 = function () { return "somethin ...

What is the equivalent of a very deep selector in TailwindCSS?

When working with the v-deep selector to customize the appearance of tiptap, a rich text editor, accessing the .ProseMirror class in SCSS would look like this: editor-content { // ... styles &::v-deep(.ProseMirror) { // ... styles } } ...

Running the nestjs build command is impossible without the existence of the node_modules folder

Currently, I am in the process of creating a Nestjs micro-service and everything is going smoothly. To run the build found within the dist folder, I use the command below: node dist/main.js However, I encountered a problem where this command does not exec ...

Is it possible to use export default Enum in TypeScript?

I am facing an issue with exporting an enum object as default at the top level in my code. Here is what I tried: export default enum Hashes{ FOO = 'foo', BAR = 'bar', } However, this resulted in an error message: Module parse failed ...