Trouble with adding multiple Vue2 components from ajax response

I'm facing an issue with appending multiple vuejs components using jquery ajax. Everything seems to be in order until the response includes more than one component, or a component within another component.

Here is the code snippet:

<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6a0a3b396e4f8e0f8e7e2">[email protected]</a>"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

<div id="app">
</div>

<script type="text/x-template" id="template-1">
    <div>
     <h1>Template 1 {{param}}</h1>
    </div>
</script>

<script type="text/x-template" id="template-2">
    <div>
     <h1>Template 2 {{param}}</h1>
    </div>
</script>


<script>
    Vue.component('template-1', {
         template: '#template-1',
         props: ['param']
       });

       Vue.component('template-2', {
         template: '#template-2',
         props: ['param']
       });

       const vm = new Vue({
           el: '#app'
       });
</script>

<script>

    function loadMore(){
        $.get('/home/test', function (response) {
            var MyComponent = Vue.extend({
                template: response
            });

          
            var compiled = new MyComponent().$mount();
            $('#app').append(compiled.$el);
        });
    }

   loadMore();

</script>

If the following response comes from ajax, it works and renders one component:

<template-1 param="Test"></template-1>

If the following response is returned from ajax, only the first component is rendered:

<template-1 param="Test"></template-1>
<template-2 param="Test"></template-2>

If this response is received from ajax, both components are rendered:

<div>
    <template-1 param="Test"></template-1>
    <template-2 param="Test"></template-2>
</div>

In case this response is returned from ajax, only the parent component is rendered:

<template-1 param="Test">
    <template-2 param="Test"></template-2>
</template-1>

Is there a way to ensure that this setup works every time without having prior knowledge of the number of components fetched from the server?

Answer №1

When instructing Vue to assign the value of response.data to the el property, it will search within it and display all registered components that are known.

In this scenario, it is advisable to always enclose your response within another HTML element, which should then be assigned as the value of the el property.

Note: Vue components nested inside other Vue elements can only render if the parent component (in this case, template-1) has registered the second one itself. This means that when template-1 is rendered, everything inside it will be removed, unless slots are used.

If you wish to utilize slots, refer to this for assistance.

Alternatively, you can explore using the render function to create your own dynamic rendering capabilities.

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

Display specific dropdown options dynamically based on MySQL query results

On my PHP page, users enter a specific ID number in a text field and click the "SEARCH" button. This triggers a PHP script to connect to a MySQL Database table named "xxx" and retrieve the row with an ID that matches the user input. The SELECT statement fe ...

Encountering a ReferenceError message that says "readFile is not defined

Currently, I am in the process of learning Node.js and encountering an issue. When I type 'node .' in the terminal, I receive a ReferenceError: readFile is not defined message. Below is the code snippet: const express = require("express"); co ...

The method of an ajax call may occasionally switch from POST to GET

When making a page with an ajax call based on user choices, I encountered an issue where even though it was specified as a POST request, it sometimes changed to a GET request. This resulted in the code in the called page failing. Upon further investigatio ...

Can you explain the process of implementing a conditional render with three parts in React?

Currently, I am attempting to implement a conditional render but encountering some issues. Is it achievable? location: `${props.off_campus_location ? ( `${props.off_campus_location}` ) : ( `${props.campus_location.name}` ) : ( `${props.location_type}` )}` ...

In Internet Explorer 11, the Content-Type setting is not functional and may cause issues with certain functionalities

My initial attempt to solve the issue involved using the method beginQuoteFileUnquoteUpload1, which created a proper boundary and Content-Type. However, upon receiving the file, I discovered that it was corrupted :( var formData = new FormData(); formD ...

Delete the final character from the value stored in the map

After retrieving data from the backend, I receive: {"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}} Utilizing Object.Keys, I filter ...

The data type 'HTMLCollection | undefined' is required to have a method called '[Symbol.iterator]()' which will then return an iterator

I'm currently working on creating a custom date-picker using web components by following a tutorial. I've encountered an error while translating the JavaScript logic to Typescript, specifically within the connectedCallback() {...} function. The e ...

What is the best way to create interactive canvases that respond to multiple clicks using JavaScript?

Within the canvas, the code snippet below aims to generate a grid of 10x10 colored boxes with alternating reddish and bluish shades on a gray background. The intention is for each canvas to only respond to mouse interactions when the mouse is within its bo ...

Implementing an Ajax load more feature for the Recent Posts widget on WordPress

I am looking to add a load more button to my Recent Posts Wordpress widget in order to fetch additional links by ajax, similar to Twitter. Can anyone point me towards a tutorial on how to achieve this? ...

Having trouble transferring information from the view (Razor) to the controller using an AJAX post request

Take a look at the controller method below: public ViewResult AddNewRow(ProjectBudgetModel model) { //Additional operations on the passed model before returning to the same view return View("AddNewProjectBudget", model); } Now, let's examine ...

Is there a way to retrieve random data based on either product id or slug within a single component using useQuery? Currently, all components are displaying the same data

Here is the code I wrote: const fetchCartItem = async () => { if (token) {const {data } = await axios.get(API.GET_PRODUCT_DETAILS_BY_PRODUCT_ID.replace("[ProductID]",item?.ProductID),{headers:{Authorization: token,},});setCartLoading(fal ...

Utilize JavaScript and HTML to show error messages based on whether the user is deactivated or if the input is invalid

I need to show different error messages under the 'Email Address' input if the user is disabled and under the 'Password' input if the user is invalid. In my debugging process, I discovered that a user being disabled results in a "Status ...

What is the syntax for implementing this function in TypeScript?

When developing applications in react and typescript, I find myself frequently creating helper functions. However, there are two key points that always give me pause. One of my functions is provided below, showcasing the common dilemmas I face. What shoul ...

spring causing css and javascript issues

*strong text*I'm a beginner in the world of Spring and I've encountered some difficulties when it comes to linking CSS and JS files. Here's an excerpt from my jsp file: <html lang="es-MX"> <head> <title>Cambio Musical& ...

Error: The value of 'PlacesService' property is not defined and cannot be read

I am working towards gathering a selection of locations that meet specific criteria by making a "routeRequest" and storing them. To achieve this, I aim to utilize Google Places to search for locations around the central point of my map. let map = new goog ...

Using javascript, how can you fill in the missing dates within an array of objects?

I need to populate this object with dates starting from today up to the next 7 days. Here is my current object: let obj = { "sessions": [{ "id": 0, "available_capacity": 3, "date": "15-05- ...

Angular 12: Running ng test shows code coverage error - TypeError: Unable to access 'initialize' property as undefined

I encountered an error in the code coverage console: TypeError: Cannot read properties of undefined (reading 'initialize') I am trying to call a service method from the component.ts file The code in the component.ts file looks like: this.myAuth ...

Seeking assistance with sending variables to a dialog in Angular 2

Currently facing an issue where I need to pass the URL id from the previous page visited by a user to a service that can be referenced in a dialog. issuer.service.ts import { Injectable, EventEmitter } from '@angular/core'; import { Observabl ...

Failed NodeJS API POST request flow issue

I am currently in the process of creating a Node and Express API specifically designed for user authentication. The data is being stored using MongoDB. When I used Postman to submit a /post request, I included the following object: { "username": ...

Guide to retrieving all selected options from a multi-select box using jQuery

I have a lengthy form that is constantly changing and includes multiple Select Options such as <select class="common_dt_select" id="select_15" data-col-index="15"> <option value="">All CC Status</option> <option value="0">De ...