Creating Vue Components indirectly through programming

My goal is to dynamically add components to a page in my Vue Single file Component by receiving component information via JSON. While this process works smoothly if the components are known in advance, I faced challenges when trying to create them dynamically. Below, you can see my attempt to use eval, which unfortunately does not work with uninstantiated objects. The code snippet provided below uses hardcoded values for illustration purpose.

<template>
  <div id="app">
    <h2>Static template:</h2>
    <InputTemplate type="text"></InputTemplate>
    <h2>Dynamically inserted:</h2>
    <div ref="container">
      <button @click="onClick">Click to insert</button>
      <br/>
    </div>
  </div>
</template>  

<script>
import Vue from 'vue'
//the component I'd like to create
import InputTemplate from './components/InputTemplate.vue'

export default {
  name: 'app',
  components: { InputTemplate },
  methods: {
    onClick() {
      //I'd like to do something like this, but eval doesn't work like this
      var ComponentClass = Vue.extend(eval('InputTemplate'))
      var instance = new ComponentClass({
        propsData: {type: 'text' }
      })
      instance.$mount()
      this.$refs.container.appendChild(instance.$el)
    }
  }
}
</script>

<p>To overcome the limitations of eval, I created a helper function that eliminates the need for manual upkeep of new components being added. Although functional, it feels a bit inelegant. Is there a more efficient approach to achieve this?</p>

<pre><code>returnComponent(componentString){
      if(componentString === 'InputTemplate'){
        return InputTemplate;
      }
    }

Answer №1

Vue surprised me with its

<component :is="yourComponentType">
feature, which is exactly what I needed to achieve my goal by using it in a v-for loop. Check out the documentation here.

Answer №2

If you're looking to fetch a component using an API, consider utilizing Async components.

I have experimented with GraphQL through Axios, but this method should function with any REST service as well.

The primary component appears as follows:

<template>
  <div>
    <h1>Test page</h1>
    <div><button @click="clicked = true">Load component</button></div>
    <async-component v-if="clicked" />
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      clicked: false,
    };
  },
  components: {
    'async-component': () => axios.post('http://localhost:5000/graphql', { query: `
      {
        asyncComponentByRowId(rowId: 1) {
          component
          content
        }
      }
    `,
    }).then((response) => {
      const comp = response.data.data.asyncComponentByRowId.content;
      // eval can be harmful
      return eval(`(${comp})`);
    }),
  },
};
</script>

The retrieved component is structured in the following manner:

{
  "data": {
    "asyncComponentByRowId": {
      "component": "my-async-component",
      "content": "{\r\n\ttemplate: '<div>{{ msg }}</div>',\r\n\tdata: function() {\r\n\t\treturn {\r\n\t\t\tmsg: 'Async component works!'\r\n\t\t};\r\n\t}\r\n}"
    }
  }
}

The decoded

data.asyncComponentByRowId.content
property represents a string that encapsulates a JavaScript object:

{
  template: '<div>{{ msg }}</div>',
  data: function() {
    return {
      msg: 'Async component works!'
    };
  }
}

Upon pressing the button, the component will display after being asynchronously fetched from the API.

An issue arises due to the usage of eval for decoding the object.

Outcome:

https://i.sstatic.net/lyf0O.png

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

Unable to utilize jQuery library in AngularJS partial HTML files, despite being loaded in the index.html file

I have been working with a web template that utilizes jQuery image gallery and other elements. Now, I am looking to convert this template into an AngularJS structure. To do so, I have created partial HTML pages like slider.html or contact.html along with t ...

The function Page.render() will output a value of false

Currently, I am utilizing phantomjs to capture screenshots of multiple webpages. The code snippet below is what I have used to generate a screenshot image. var page = require('webpage').create(); page.viewportSize = { width: 1200,height: 800}; ...

How to Align Text at the Center of a Line in Three.js

Exploring What I Possess. https://i.sstatic.net/nAtmp.png Setting My Goals: https://i.sstatic.net/svcxa.png Addressing My Queries: In the realm of three.js, how can I transform position x and y into browser coordinates to perfectly align text in th ...

The jQuery function $.fn.myfunction appears to be malfunctioning

Here's the code I'm working with: [[A]] // jquery.fn.code (function( $ ){ $.fn.flash = function(duration) { this.animate({opacity:0},duration); this.animate({opacity:0},duration); }; })( jQuery ); 1. $(document).ready ...

Issues encountered when using .delay() in conjunction with slideUp()

Issue: The box is not delaying before sliding back up on mouse out. Description: Currently, when hovering over a div with the class ".boxset" called "#box", another div "#slidebox" appears. Upon moving the mouse away from these two divs, #slidebox slides ...

Sending data to a function that is generated dynamically within a loop

How can I ensure that the date2Handler is triggered with the corresponding date1 and date2 values from the month in which the date1 change occurred? Currently, whenever the date1 value is changed in any month, the date2Handler is called with the "month" t ...

Toggle the visibility of a section in an external .js file

Is there a way to toggle the display of answers from an external .js file using a button? If I were able to modify the code, I could wrap the answers in a div. However, since it's an external .js file, is this feasible? Here's the fiddle and cod ...

Changing Marker Colors in OpenLayers After Importing GPX Data: A Quick Guide

Check out this link for a code tutorial on importing GPX files and displaying map markers. I successfully implemented this code to show map markers. Is there a way to customize the color of the markers? Edit: var fill = new Fill({ color: 'rgba(2 ...

eliminate a mesh from the view following a mouse hover event triggered by a raycaster

            When loading a gltf model, I want to make sure that a mesh is only displayed when the object is hovered over. I have successfully managed to change its material color using INTERSECTED.material.color.setHex(radioHoverColor); and reset it ...

The responses for several HTTP POST requests are not being received as expected

I am facing a challenge in retrieving a large number of HTTP POST requests' responses from the Database. When I try to fetch hundreds or even thousands of responses, I encounter issues with missing responses. However, when I test this process with onl ...

An error occurred in Node.js while parsing data: Headers cannot be set after they have already been sent to the client

I am currently using a CSV parser to read data from a CSV file. I then pass this data in object format to an EJS template file for printing. However, when I try to stringify the data, I encounter an error. The error message is as follows: Error [ERR_HTTP_ ...

Tips on how to optimize form input mapping without losing focus on updates

I am facing an issue with a form that dynamically renders as a list of inputs. The code snippet looks like this: arrState.map((obj,index)=>{ return( <input type="text" value={obj} onChange{(e) => stateHandler(e,index)}<inpu ...

Is it possible for a prop to change dynamically?

I am currently developing a component that is responsible for receiving data through a prop, making modifications to that data, and then emitting it back to the parent (as well as watching for changes). Is it possible for a prop to be reactive? If not, wh ...

Adjusting the size of tables in raw JavaScript without altering their positioning

I am attempting to adjust the size of a th element without impacting the position of the next th in the row. Specifically, I want the width of the th to influence the width of the next th accordingly, rather than pushing it to the left. Below is the code ...

Using React: Passing the state value of Child1 to the Parent component, then passing it back down to Child2 from

Within my application, I've implemented two child components: 'FoodScreen' and 'OperationScreen', along with a parent component called 'Desk'. I am passing a JSON array variable to the FoodScreen component in order to sel ...

What is the explanation behind the functionality of "this.$store._modules.root" in nuxt?

Hi there, I'm just starting to learn JavaScript and Vue. (I apologize if my question sounds silly or if my English is not great.) I decided to try console.log(this) in Nuxt out of curiosity, and was surprised to see a huge object. Here' ...

Identifying when two separate browser windows are both open on the same website

Is it possible to detect when a user has my website open in one tab, then opens it in another tab? If so, I want to show a warning on the newly opened tab. Currently, I am implementing a solution where I send a "keep alive" ajax call every second to the s ...

Encountering a popup_closed_by_user error while attempting to test Google OAuth within my web application

Currently, I am working on integrating Google login into my web application using AngularJS. Whenever the popup opens up for logging into my Google account or selecting an existing account, I encounter an issue where the popup closes with an error message ...

What is the best way to ascertain the variance between two Immutable.js Maps?

I currently have two unchangeable maps: const initial_map = Map({x: 10, y: 20)} const updated_map = Map({x: 15, y: 20)} Can anyone advise on how to find the changes between the two maps? The expected outcome should be: Map({x: 15}) ...

Access real-time information via JSON

I am facing a logical thinking challenge. Successfully retrieving data from a PHP file via JSON, but now encountering a slight issue. My goal is to retrieve various headlines - main and sub headlines. Each main headline may contain an unknown number of su ...