Rendering a dynamic list of asynchronous components in Vue 3, with support for extension

Could you please assist me in resolving this issue?
I've spent countless hours searching for a solution, but I can't seem to make it work. Vue is still very new to me.
Let me provide some more context.

I have an asynchronous component that is generated upon request. It has a template that organizes a form based on received JSON data. The component is being created successfully and loading all the fields correctly. Here is the structure:

<template>
  <div class="constraint_supercontainer col-lg-12">    
    <form class="constraint_group" v-for="constraint in constraints.data.constraints" :key="constraint">
      <div class="constraint_field">
        <label class="constraint_label">{{constraint.label}}</label>
        <select class="constraint_select" v-bind:name="constraint.name" v-bind:id="constraint.name">
          <option value="" selected disabled>-- SELECT --</option>
          <option v-for="value in constraint.values" :key="value" v-bind:value="value['value']">{{ value['label'] }}</option>
        </select>
      </div>
    </form>
  </div>
</template>

<script>
const api_route = "<api_route>";

export default {
  name: 'Constraint',
  async setup(){
    const response = await fetch(api_route+'get-conditions');
    const constraints = await response.json();

    return { constraints }; 
  } 
};
</script>

Everything is working fine up to this point. However, in my main app constructor, I need to be able to create multiple instances of this component (Constraint) and render them within the same DOM element. In Vue2, I was able to achieve this using the Vue.extend function, which unfortunately no longer exists in Vue3. In Vue3, this functionality only works for the first element, and subsequent calls result in an error. Below is the structure of my main component:

<template>
  <div id="app">
    <div class="toolbar">
      <button @click="add">Add conditional group</button>
    </div>
    <div id="constraints_list" ref="constraints_list">
      <div v-for="item in constraints_group" :key="item">
        <Suspense>
          <Constraint></Constraint>
        </Suspense>
      </div>
    </div>
  </div>
</template>

<script>
import Constraint from './components/Constraint'
import { h } from 'vue';

export default {
    name: 'app',
    components: { 
        Constraint 
    },
    data() {
      return {
        constraints_group: [],
        constraint_count: 0,
        constraint:{
            gender: null
        }
      }
    },
    mounted () {
      this.addConstraintBlock();
    },
    methods: {

      addConstraintBlock() {
          this.constraint_count++;
          let instance = h(Constraint);
          this.constraints_group.push(instance);
      }
    },
}
</script>

Here is the error I encounter when attempting to create a second instance: Error encountered while creating second component following the same steps as the first one

I came across a post at https://www.reddit.com/r/vuejs/comments/iwc7o4/vue3_what_happen_to_vueextend/ where someone "created a workaround for the Vue.extend function",but unfortunately, the project didn't work for me and gave me the following error:

Failed to compile.

./node_modules/mount-vue-component/dist/index.cjs.js 11:10
Module parse failed: Unexpected token (11:10)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| 
|   let vNode = vue.createVNode(component, props, children);
>   if (app?._context) vNode.appContext = app._context;
|   if (el) vue.render(vNode, el);
|   else if (typeof document !== 'undefined' ) vue.render(vNode, el = document.createElement('div'));

I tried to understand how to use that loader, but despite installing it and configuring babel.config.json as suggested, I had no luck. I also attempted to recreate the code in the project, but it didn't work either.

At this juncture, I am out of ideas. Despite trying various solutions, everything results in an error. If anyone could offer me some guidance, a solution, or any insight, I would be extremely grateful.

Answer №1

My perspective is that this discussion pertains to Vue in a broader sense rather than just focusing on Vue 3...

In Vue, it's rare to create component instances within the <script> block (although some individuals might do so out of misunderstanding). Vue operates on a "declarative" and "data-driven" model. This means that your template output is determined by data - instead of creating components, you manipulate the data and the template will automatically generate components based on that data...

Take a look at this straightforward example:

const piece = Vue.component('Piece', {
  props: ['number'],
  template: `<div> Piece {{ number }} </div>`
})

const app = new Vue({
  el: "#app",
  components: { piece },
  data() {
    return {
      counter: 0,
      pieces: []
    }
  },
  methods: {
    addPiece() {
      this.pieces.push(this.counter)
      this.counter++
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button type="button" @click="addPiece">Add Piece</button>
  <hr>
  <Piece v-for="piece in pieces" :key="piece" :number="piece"/>
</div>

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

Share the hyperlink to a webpage with someone else

In my SQL command, I have a unique feature that retrieves the complete URL value of the current page: [##cms.request.rawurl##]. This code returns the entire URL. I need to send this address to another page and load it into a special div called "load-fac". ...

An issue arises when attempting to utilize the 'push()' method to append a string to a JSON array

I am looking to append strings to my JSON file structure shown below: { "items": [] } To achieve this, I have the requirement of using the following code: var items = require("../../config/item.json"); The approach I am taking is ...

Revealing the Webhook URL to Users

After creating a connector app for Microsoft Teams using the yo teams command with Yeoman Generator, I encountered an issue. Upon examining the code in src\client\msteamsConnector\MsteamsConnectorConfig.tsx, I noticed that the webhook URL w ...

Launching ExpressJS and ReactJS on Heroku

Currently working on a project that combines express and react. When attempting to deploy it to Heroku via git push, I encountered an error upon checking the heroku logs. The specified webpage then shows a message indicating that it cannot locate a build ...

Loop through unique IDs using AngularJS ng-repeat

I am just starting to delve into AngukarJS and ionic framework, embarking on the journey of creating an app with a structured tree layout as follows: Home Tab (list of books) (templates/allbooks.html) > unique book (book description and chapters) (tem ...

Node.js - updating the value of a exported integer variable

In my file A.js, I have defined a module-level variable called activeCount and exported it using module.exports. In another file named testA.js, I am attempting to access and modify the value of activeCount. Despite my efforts, changes made to activeCount ...

Executing a Ruby function via AJAX

I am fairly new to working with ajax, and I find myself in need of using it for my Rails application. Here is the function in my controller: def check_code input = params[:input] code = params[:code] if input == code return true else retur ...

Manipulate text within a text area using jQuery

Good afternoon. How can I use JavaScript to update the text in a textarea input? I currently have some content in my textarea that includes a PublisherImprintName tag, and I want to remove it using jQuery. <PublisherInfo> <PublisherName>A ...

Guide on integrating Vue JS code into a .Net MVC project

I am facing a challenge when trying to integrate a Vue JS folder containing index.html, main.css, main.js, and vue.js into a .Net MVC project. I have limited knowledge about .Net and how it functions, but I understand where the CSS files need to go in the ...

Allow undici fetch requests to use self-signed certificates

What is the correct way to execute fetch('https://localhost:8888') when dealing with a locally hosted HTTP server that uses a self-signed certificate (using fetch which is derived from undici)? ...

Customize a div's background color with an Angular directive

Imagine having a div element: <div id="wrapper"> some text </div> How can you create an angular directive that changes the background based on user input? For instance, you might have tried: <div id="wrapper" color temperature="51"> ...

working with Selenium in the Chrome web browser

Within a file named e2e.js, the following code was written: const webdriver = require('selenium-webdriver'); const driver = new webdriver.Builder().forBrowser('chrome').build(); driver.get('https://www.google.co.il/'); I h ...

Show a popover within a parent div that has limited visible space due to its hidden overflow

Struggling with AngularJS, I can't seem to find a simple solution for this problem. In my code, there's a div element with the overflow: hidden property set due to an internal scrollbar. Inside this div, there's a dropdown menu that is trigg ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

What is the process for incorporating Express.js variables into SQL queries?

Recently delving into the world of node.js, I've embarked on a journey to create a login and registration system using express.js, vanilla JS, CSS, HTML, and MySql. Within the following code lies the logic for routing and handling HTTP Post requests ...

There seems to be an issue with FastAPI not sending back cookies to the React

Why isn't FastAPI sending the cookie to my React frontend app? Take a look at my code snippet: @router.post("/login") def user_login(response: Response, username :str = Form(), password :str = Form(), db: Session = Depends(get_db)): use ...

Cracking the code of the @ symbol within this particular context

https://github.com/react-dnd/react-dnd/blob/master/examples/04%20Sortable/Simple/Card.js I'm trying to comprehend the significance of the @ symbol in this example. This is meant to be a straightforward drag and drop demonstration, but the implementa ...

React - Issue with Material-UI radio button group not filling button upon clicking

I've been working on an app using React and incorporating Material-UI components. In a specific section of the interface, there are four options that users can toggle between with radio buttons. Despite setting up the rendering correctly, I encountere ...

TypeError: The function cannot be performed on the value of 0 in the Array.from

I encountered a peculiar error while attempting to utilize Array.from with Array.prototype.map. let fn = Array.from.bind(Array); // [Function: bound from] fn('test') // [ 't', 'e', 's', 't' ] ['test ...

Error with decodeURIComponent function in Internet Explorer 8

My widget, loaded as an iframe, requires data about the hosting page. I have UTF-8 strings extracted from a page with Russian text. The page itself has proper HTML5 doctype and meta charset. This is how my code operates: params = "x1=" + encodeURICompone ...