Guide to dynamically loading a component using a variable name in Vue.js?

Is it possible to dynamically load a component in a vue.js application using a variable name?

For example, if I have the following component registered:

<template id="goal">
  <h1>Goal:{{data.text}}</h1>
</template>

Instead of directly loading it like this

<goal></goal>

I'm looking for a way to load it from a variable name, something like this:

<{{mytemplate.type}}></{{mytemplate.type}}>

In this scenario, mytemplate.type would be equal to "goal". Is there a way to achieve this in vue.js?

Answer №1

Implement a dynamic component in the following manner:

<component :is="myTemplate.type"></component>

Answer №2

I encountered a similar issue while using Vue 3. After conducting some research, I discovered that the process of defining dynamic components (async components) differs slightly in Vue 3. I hope this code snippet proves helpful to someone.

<template>
    <component :is="comp"></component>
</template>

<script>
//Vue 3 incorporates a special function for defining async functions
import {defineAsyncComponent} from "vue";

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

Answer №4

Although @Rakshit's response seemed valid, I personally found it unnecessary to include such complexity in my solution. In case anyone else is facing a similar situation and needs to reference a different component for each v-tab in vuetify3, the following code worked well for me:

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

Regarding the script section, this approach was taken:

import ThatModule from "./ThatModule.vue";

export default {
  name: "CategorizeModule",

  data: () => ({
    tab: null,
    items: [
      {
        name: "Spending",
        component: <ThatModule></ThatModule>,
      },

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

Tips for implementing permission-based functions in a React frontend with a Django Rest API

I am currently using Django Rest Framework in conjunction with React on the frontend. Utilizing Token Authentication has been successful for me thus far. Now, I am looking to add permission-based functions to my React frontend. Specifically, I want only th ...

Understanding the error handling in Express.js

Learning about error handling in express is new to me and I have a straightforward piece of code like this - const express = require('express'); const MongoClient = require('mongodb').MongoClient; const app = express(); let url = &a ...

Can anyone provide guidance on locating the parent of a pseudo element with Selenium WebDriver?

Is there a way to retrieve the parent web element of a pseudo element (if we can call it the parent) using JavaScript? I know that Selenium's methods for searching for web elements are not suitable for pseudo elements, but JavaScript does allow manipu ...

Encountering an Error while Setting Up NextJS on Vercel

Hello, I'm a newcomer to the world of web development. My current goal is to deploy my first NextJS app on Vercel, but I keep encountering an error. Error: SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) ...

Why does my ngFor consistently refresh while the array remains unchanged?

Issue at hand: Whenever I launch this component, the ngFor div continuously updates and causes my RAM to deplete. Typically, ngFor is triggered when the array is updated; however, in my case, the array (announcements) only updates once in the constructor. ...

Display a Vue.js div element based on conditions matching a specific variable value

Is it possible for Vue.js to display a div only when a defined variable is set to a specific value? Currently, v-show="variable" can be used to show the div if the variable is set. However, I would like to know if v-show="variable=5" can be implemented t ...

Error in Next.js: The function (0 , firebase_auth__WEBPACK_IMPORTED_MODULE_1__.onAuthStateChanged) is not defined as a function

Just starting out with Next.js development and currently following a Youtube tutorial on creating a Whatsapp clone using firebase8.9 as the database. I am looking to implement a feature where the app checks if the user is logged in, if so redirect them to ...

Styling the jQuery location picker input with background and focus effects

While working on a web app using jQuery locationpicker, I noticed that it's causing some styling issues with the input. Despite being able to adjust properties like width, padding, and border, changing the background requires using jQuery. Here is th ...

Navigating a Vue.js realm: Transferring card button ID to backend URL pathway upon clicking

Within my DisplayBooks.vue component, I have implemented a feature where users can update a book card by clicking on the ADD TO BAG button. This update is triggered by calling the handleCart() method which takes care of updating the book based on its id. M ...

Retrieving variables using closures in Node.js

I have been developing thesis software that involves retrieving variables within closures. Below is the code snippet written in node.js: var kepala = express.basicAuth(authentikasi); // authentication for login function authentikasi(user, pass, callback ...

Managing multiple to-do lists within a React application using parent-child relationships

ReactJS has a flaw that I've come across while trying to create a Todo application using Redux for state management. The issue arises when dealing with nested JSON data, such as having parent and child nodes in the response from a database query. Red ...

What is the best way to integrate a Vue component into a Knockout application?

My webpage is filled with knockout code, but I'm hoping to integrate a Vue.js component for a specific section. I attempted using controlsDescendantBindings on a surrounding tag for the Vue component, and it seems to be partially functional (I tried ...

What is the browser location for storing JavaScript constants?

How can I retrieve the value of a constant using a string as its name, where the constant is an arrow function? const foo = (bar) => { return bar } I tried accessing it through the window object but got undefined: let fn = window['foo'] // ...

Using Vue 3 to have the ability to include multiple composable instances in a single script tag

Currently in the process of revamping our components that are originally built using the Options API. A key point for refactoring from a code-cut perspective is how we handle our multiple modals, each with their own open/close and boolean logic scattered t ...

How can I retrieve a DOM object following an AJAX request?

My AJAX call fetches and appends HTML content to the current page. I hope to access this newly added HTML using standard jQuery selectors. Here's my desired approach... $.ajax({ url: url, success: function(data) { $('body').app ...

html and css code to create a linebreak ↵

I received a JSON response from the server, and within this data is a "return line" in the text. {text: "I appear in the first line ↵ and I appear in the second line"} However, when I try to display this on an HTML page, the "return line" does not show ...

Is there a way to generate and transmit a text file using XmlHttpRequest or $.ajax?

The server is anticipating an html or txt file to be sent from a form named "websitetopdf". The file is dynamically created on client javascript and should only function properly on Chrome. Below is the form that needs to be used for sending: <form ac ...

Reactjs encountering issues with function of Cookies section

Currently, I am working on a login module in Reactjs using Nextjs. Upon successful login, I am storing the user email in a cookie. The functionality is working as expected, but I want to restrict access to the login page for users who are already logged in ...

Issue: Unable to open port (GetCommState) : Error code 1 not recognized - Utilizing Nodejs, express, SerialPort

I am currently attempting to establish a connection between a fiscal printer with serial input and nodejs. I am utilizing the SerialPort module, but encountering difficulty in establishing the connection. The console is displaying the following error messa ...

What is preventing Backbone from triggering a basic route [and executing its related function]?

Presenting My Router: var MyRouter = Backbone.Router.extend({ initialize: function(){ Backbone.history.start({ pushState:true }); }, routes: { 'hello' : 'sayHello' }, sayHello: function(){ al ...