Displaying components in Vue 2 using data from an ajax call

How can components retrieved from an ajax response be rendered? For instance, suppose I have registered a component called "Test" and within the ajax response I encounter:

<p>dummy paragraph</p>
<test></test> <!-- vue component intended for rendering -->
<p>another dummy paragraph</p>

My ultimate objective is to create a shortcode that enables users to insert a router link in the content section.

The technologies being used are Vue 2 and Vue Router.

Edit: Check out this demonstration https://jsfiddle.net/Paulius_Krutkis/4mb1ypqs/

Answer №1

I'm uncertain about the specific issue you're encountering here. If you're seeking a way to display the HTML returned from an ajax call, you can utilize v-html, which can render a string variable containing HTML.

However, please note:

The contents are inserted as plain HTML - they will not be interpreted as Vue templates.

Therefore, v-html won't interpret and render any vue component as expected. You may need to explore other solutions for this.


Alternate Approach

Since you mentioned needing a method to render components retrieved from an ajax response, you can utilize Async-Components. Here, you define your component as a factory function that asynchronously resolves your component definition.

Check out the demo here: https://jsfiddle.net/4mb1ypqs/1/

Answer №2

Indeed, there is a way to accomplish this task. Simply follow these instructions:

  1. Begin by registering the component (which will be sent as an ajax response) globally.
import Vue from 'vue'
import Test from './some/folder/Test.vue'

Vue.component('test', Test)
  1. You can either add Vue to the window object or export it for later importing wherever necessary. For simplicity, I will add it to the global window object for easy access in the browser console.
window.Vue = Vue
  1. Once you receive the ajax response containing the uncompiled DOM element (<test></test>), you have the option to insert it directly into your DOM and compile it afterwards, or compile it first before mounting it to the DOM. Assuming you inserted the component template directly into the DOM as shown in your example, pay attention to the wrapper element.
<p>dummy paragraph</p>
<div id="testapp">
  <test></test>
</div>
<p>another dummy paragraph</p>
  1. Next, create a new Vue instance and specify where it should be mounted. Since your test component is already registered globally, Vue recognizes its structure and will compile it upon encountering it in the DOM. Alternatively, you can also include it within the "components" property here.
new window.Vue({
    el: '#testapp',
})
  1. That's it!

Note: If you have a root vue instance already mounted, VueDevtools may not detect your newly compiled component. To address this, you need to inform the newly created instance that it belongs to a parent instance:

var vm = new Vue({ 
  el: '#app',
});

new window.Vue({ 
  el: '#testapp', 
  parent: vm,
});

Important: The new vue instance will NOT share data with other instances. This method is primarily useful when dealing with independent components, such as a text-input component designed solely for sending data to the server independently.

I trust this information proves helpful to someone in need!

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

What is the best way to find a match for {0} while still allowing for proper

I am working on developing a text templating system that allows for defining placeholders using {0}, similar to the functionality of .Net's string.format method. Here is an example of what I am aiming for: format("{0}", 42), // output ...

Deactivate a span in real-time using ng-model

I found a helpful guide on creating a custom editable <span> using ngModelController here: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#example Now, I am looking to implement a feature that allows me to dynamically disable editin ...

developing a dynamic map with javascript

In the image provided, my concept is for it to initially be without a green tint. However, when the user hovers over specific areas, they would turn green and become clickable links. There are multiple areas in the image, with this being just one example. ...

The smooth scrolling feature fails to function properly in Lenis when clicking on links with specified IDs

Is there a reason why the scroll-behavior: smooth property doesn't function properly when Lenis library for smooth scrolling is included? It seems to work fine when the Lenis code is commented out, but once it's added back in, the scrolling isn&a ...

Begin using datatables with the xp:table component

Within an XPage, there is a table component: <xp:table id="tblProposals"> I am looking to apply the datatables plugin to this table using a scriptblock component: <xp:scriptBlock id="scriptInitProposals"> < ...

Prevent automatic scrolling to anchors when using router.push() in Next.js

When using the latest version 10.2 of next, every time a URL with a hash is pushed to the router, next.js automatically jumps to the anchor element. import {useRouter} from 'next/router' router.push('/contact#about-us'); This behavior ...

What's the process for including delivery charges in Stripe transactions?

I am facing an issue with Stripe where I am unable to incorporate delivery fees into my transactions. How can I successfully integrate this feature? let line_items = []; for (let productId of uniqIds) { const quantity = productsIds.filter(id => id == ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

if considering an integer value of 0 as equivalent to null

I am struggling with using axios to send data to an API in react. Despite the server successfully receiving the values, my code is not entering the if block as expected. Interestingly, when I make the same request from a rest client, it works perfectly. He ...

What could be causing my node.js to fail in producing a true result within the return statement?

I've encountered an issue with VS code where the return true command is not displaying anything in my terminal, while console.log(map[arr2[j]]) successfully returns true. I'm unsure if this problem lies with node or my terminal. How can I ensure ...

Uncertain about the type of data to send back for Ajax requests in Django?

Looking to improve the functionality of my like button by making it asynchronous using JavaScript. Currently, when I like a post and refresh the page, the like count increases. However, I want the like count to increase without refreshing. To achieve thi ...

Transfer information from one Angular JS page to another pager based on ID

In my use of the mobile angular js UI framework, I am a beginner in angular js and looking to transmit data from one page to another using city id. When a user clicks on a city, the data should be displayed according to that specific city. HOME PAGE: ht ...

Incorporating SEO for a Flash-Based Website

After reading through various discussions on this topic, it seems like my question still remains unanswered. We are gearing up to revamp our company's website in the coming months. Currently, our site is mostly text-based, which has helped us achieve ...

Determining if a Turbolinks request is made in a Rails controller

I'm currently working on a Ruby on Rails 4 project that utilizes the Turbolinks gem. One interesting observation is that when a link is clicked, the layout is still rendered server-side, but the Turbolinks JavaScript only grabs the body portion of thi ...

Issue with Semantic-UI Special PopUp not displaying on screen

I'm currently working on creating a unique pop-up feature using custom HTML, with the intention of adding content to it later on. My console is displaying the following message: Popup: No visible position could be found for the popup. $(document) ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Implement a friend request feature with jquery and ajax

I'm working on implementing an add friend system for my website. Here's the code I have so far: HTML: <a href="" id="add_friend">Add this user</a> jQuery: <script type="text/javascript"> $(document).ready(function(){ $(& ...

Customize the antd theme in a create-react-app project without the need to eject webpack

Struggling with customizing antd in my react app. I'm hesitant to mess with the webpack config.js file since I'm not well-versed in webpack. My goal is to avoid having a site that looks like a generic antd clone, but all my attempts at customizat ...

Tips for choosing between options in JavaScript and AngularJS

How can I choose the appropriate <select> tag option using JavaScript or AngularJS in the backend? Hint: I receive data from an API service and populate a form for editing. Assuming the gender is currently set as Male in the database, how can I disp ...

What steps do I need to follow to send an AJAX request to a REST API using CakePHP?

My CakePHP user component includes add/update/delete controllers that function as REST API methods. Now, I am looking to trigger these controllers through an AJAX or HTTP request. This REST API will be utilized by a mobile app. Thank you for your assist ...