Is it possible to dynamically call a component in Vue.js using a variable name

Can a Vue.js component be called by using a variable name?

The components are registered like this:

import Component1 from 'component1'
import Component2 from 'component2'
import Component3 from 'component3'

...

components: {
    Component1, Component2, Component3
},

I am exploring the possibility of something like this:

created() {
    var componentName = 'Component1';
    this.components[componentName]
}

Answer №1

To retrieve the components property, you can use the following syntax:

this.$options.components[componentName]

Answer №2

Here is a simple demonstration of how dynamic components can be utilized:

Feel free to experiment with the code on jsFiddle: link here

<div id="app">
   <component v-bind:is="currentPage">
       <!-- the component changes based on the value of currentPage! -->
       <!-- output: Updated About -->
   </component>
</div>

new Vue({
  el: '#app',
  data: {
    currentPage: 'home'
  },
  components: {
    home: {
      template: "<p>Home</p>"
    },
    about: {
      template: "<p>About</p>"
    },
    contact: {
      template: "<p>Contact</p>"
    }
  },
  mounted(){
   this.$options.components['about'].template = "<p>Updated About</p>"
    this.currentPage = 'about'
  }
})

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

Troubleshooting a Non-Responsive React onClick Event in ES6

I am a beginner in React and have been searching on various platforms like StackOverflow and the internet, but I cannot figure out why onClick is not working in my case. When I click the button, absolutely nothing happens. I have tried everything from putt ...

Tips for making WebDriver pause until Sencha AJAX request finishes

While testing a page with Selenium WebDriver, I encountered an issue related to the Sencha JavaScript library being used on the underlying page. The problem arises when I input a value into a field and an AJAX call is made to validate that field. If the va ...

Modify the selected toggle buttons' color by utilizing the MUI ThemeProvider

I am currently working on customizing the color of selected toggle buttons within my React app using TypeScript and ThemeProvider from @mui/material 5.11.13. Despite my efforts, when a toggle button is selected, it still retains the default color #1976d2, ...

Adding a unique key to every element within a JavaScript array

I am working with the array provided below which contains simple values. My goal is to add a key id before each value in the array, resulting in something like this: ["id:a", "id:b","id:c","id:d"]. Is there an easy way to achieve this? Any assistance would ...

VueJs: Checking if a component is mounted within a watcher

It seems like a straightforward requirement, and although I could track it myself using lifecycle hooks, I'd prefer to utilize existing built-in functionality. I believe VueJs must maintain the component's lifecycle state internally. Below is a ...

Vue.js is unable to dispatch an event to the $root element

I'm having trouble sending an event to the root component. I want to emit the event when the user presses enter, and have the root component receive it and execute a function that will add the message to an array. JavaScript: Vue.component('inp ...

When attempting to utilize res.sendfile, an error arises indicating that the specified path is incorrect

I am facing an issue with my Express.js server and frontend pages. I have three HTML and JS files, and I want to access my homepage at localhost:3000 and then navigate to /register to render the register.html page. However, I am having trouble specifying t ...

Is it possible to adjust the center of rotation in THREE.js TrackballControls so that it is not located at the center of the canvas

I'm currently using TrackballControls within THREE.js. The issue I am facing is that the center of rotation always remains in the center of the canvas. Is there a way to adjust this and move the center of rotation upwards? Here are my failed attempts: ...

How can I retrieve and showcase the size of each file, including images, CSS, and JS, present on a website?

Currently, my goal is to create a dashboard capable of retrieving the file size for all resources (images, javascript, css, etc.) loaded on a webpage. I aim to then further filter these resources by file type and file size in order to identify which ones c ...

Is it possible to alter objects through the use of jQuery.map?

I'm working with a key-value pair that looks like this: var classes = { red: 'Red', green: 'Green' }; Is there a way to add a specific value before each key in the pair? Can jQuery.map help with this task? The desired end result ...

Leveraging nodemailer and handlebars for personalized email templates

I'm encountering an issue and struggling to pinpoint what exactly is causing it. Whenever I execute my code, the following error message pops up: [Error: ENOENT: no such file or directory, open 'C:\Users\Alex\Desktop\emailtes ...

Is it possible to showcase two modals on a single page, positioning one to the left and the other to the right using Bootstrap?

Can someone help me learn how to display two modals on the same screen, one on the left and one on the right? I am new to bootstrap and would appreciate some guidance! ...

Typing the url in the address bar when using Angular's ui-router

Two distinct states are present: .state('test', { url: '/test', templateUrl: 'js/angular/views/test.html', controller: 'UserController', }) .state('test.list', { url: ' ...

Why is it necessary to include 'export' when declaring a React component?

When working with React (ES6), there seems to be two variations that I encounter: class Hello extends React.Component { ... } and sometimes it looks like this: export class Hello extends React.Component { ... } I'm curious about the significance o ...

Guide on creating a cookie verification process with no contents

Request for Assistance: let cartHelper = { cartCookieName: "_cart", getCart: function (callback = undefined) { return apiHelper.getRequest( "/carts", (response) => { documen ...

Utilizing Javascript or XUL windows without the use of iframes offer

I'm in the process of creating a multitab website for my bookmarks, but I've run into some issues. Here is the JavaScript version of what I'm trying to achieve: Unfortunately, there are obstacles with this method. The websites in the tabs ...

Tips for aligning the first element in an inline-block list item horizontally

I'm working on a list with horizontal scroll functionality to allow users to view content by scrolling. I have successfully implemented this, but I'm facing a couple of challenges that I need help with: I want the first item in the list to alwa ...

Navigating the elements within R Shiny: A comprehensive guide

Can anyone help me figure out how to access specific elements in my Shiny app using their HTML tags? In this particular example, I need to retrieve all h1 elements along with their respective labels and IDs. library(shiny) ui <- fluidPage( h1("Get" ...

Ajax is working effectively as the first post is successful and the second post is able to retrieve data

UPDATE: I resolved the issue by relocating my form submitter script from the Header to the bottom of the jamesmsg.php page (the included one). By doing this, the functions are always re-loaded and attached to the "new" form each time the div is refreshed. ...

"Utilize Node.js to seamlessly stream real-time Instagram photos based on a designated hashtag

Does anyone know of a node.js library or solution that can automatically fetch Instagram photos in real-time based on specific hashtags? ...