Guide to retrieving the compiled HTML content of a Vue.js component

I have a component structured like this

<AgentCard :agent="agent" />
, with the object agent containing properties such as
FirstName, LastName, Recent Orders
, and more.

My current challenge involves displaying this component inside a Google Maps InfoBox. The infoWindow.setContent() method (which is part of the Google Maps API used to showcase popup info windows) only accepts an HTML string. Therefore, I am attempting to manually render the <AgentCard>, extract the HTML content of the rendered component, and then pass it on to the setContent() method.

I made an attempt using

Vue.compile('<AgentCard :agent="agent" />').render()
, but unfortunately, this approach did not work. How can I go about manually rendering a Vue component and obtaining its HTML content?

Answer №1

One way to solve this issue is by initializing a fresh Vue instance containing solely the targeted component, then utilizing $mount to mount it. Subsequently, you can obtain the outerHTML of its root element ($el):

<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="691f1c0c295b475f47585b">[email protected]</a>/dist/vue.min.js"></script>

<script>
Vue.component('AgentCard', {
  template: `<div>{{agent.name}}</div>`,
  props: {
    agent: Object
  }
})

const app = new Vue({
  template: `<AgentCard :agent="agent" />`,
  data: () => ({ agent: { name: 'john doe' } })
}).$mount()

console.log(app.$el.outerHTML)
</script>

Answer №2

When using Vue3:

import { createApp } from "vue";    
const newDiv = document.createElement("div"); 
createApp(MyComponent, { myProp: "here" }).mount(newDiv); 
console.log(newDiv.innerHTML); 

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

Ways to retrieve a specific value from a JSON dataset

I currently have an Ajax live search script with multiple text inputs for searching products. The live search functionality works perfectly, but I have a query: If I decide to change the name of a product, how can I go back to the previous page and re-s ...

Ways to access PromiseValue in XMLHttpRequest with JSON

Is there a way to access an array that is within the PromiseValue instead of receiving Promise {<pending>} When I use .then(data => console.log(data)), I can see the array in the console log. However, my requirement is to display this array on an ...

What is the best way to pass a JSON object from R to Plumber in a format that JavaScript can interpret as an array instead of

My goal is to receive a JSON raw response from R Plumber and then utilize it in Angular. However, I am encountering an issue where the JavaScript Framework is interpreting it as a string instead of recognizing it as JSON format. "[{\"id&bsol ...

Obtain the parameter value from the resolve function in ui-router

Using window.open, I plan to open a URL such as https://localhost:3000/new?HostId=8Ocs_Onuv1wowozxAAAS&_host_Info=excel%7Cweb%7C16.00%7Cen-us%7Cc8b501ce-c51d-b862-701e-5c623e1a70e0%7CisDialog. The site https://localhost:3000 hosts a MEAN stack applica ...

Node.js woes: troubleshooting object output issues

I am currently delving into the world of Node.js and express as I explore building a simple bike configuration. I have created an object that encompasses all the necessary properties for this project. After exporting this object, I attempted to display it ...

Developing entities in Express.js

My express app is currently fetching data from an external API through the following endpoints: api.com/companies (GET, POST) api.com/companies/id (GET, PUT) To improve maintainability and avoid code repetition, I am looking to create a model for handlin ...

Check to see if the upcoming birthday falls within the next week

I'm trying to decide whether or not to display a tag for an upcoming birthday using this boolean logic, but I'm a bit confused. const birthDayDate = new Date('1997-09-20'); const now = new Date(); const today = new Date(now.getFullYear( ...

Tips for adding a string variable to a JQuery HTML element attribute

Hi there, I've been working on a JQuery code to append data to a div element and it's been successful so far. Here is the code: $('#conversation').append('<div id="receiver"><p><b>' + username + ':< ...

The status value in the result has a whitespace just before the term "success"

Apologies for the unclear question, but I encountered a strange bug in my code. I am trying to show an alert to users informing them that the updates have been successfully completed. Below is the code snippet containing an if() block where the alert shoul ...

VueJS - The application is unable to find the designated route

I've encountered an issue with the Signin page in my project. Despite having all other pages functioning properly, the Signin page doesn't seem to render anything when I navigate to it (http://localhost:8080/#/signin). import Vue from 'vu ...

Exploring the world of jQuery waypoints and the art of modifying

This is only the second question I'm asking here, so please be gentle! I've been experimenting with jQuery waypoints to dynamically show and hide a border under my navigation menu based on scroll position. For instance, when the sticky nav is ov ...

Unable to adjust the size of a DIV with a button click in Vue3

I am having trouble resizing a DIV block in Vue3. Whenever I click the button, I receive an error message saying "Cannot read properties of undefined (reading 'style')". I know there is an issue with the JS part of the code, but I'm not sure ...

I am consistently encountering the error message: "Error: Unable to locate module './framer'"

I've been running into the same issue repeatedly. I'm in the process of creating a website for a barbershop and I'm attempting to integrate events into a Google calendar using the Google API. I've installed googleapis and framer, but I ...

What steps should I take to create a JavaScript-based downloader application?

I am looking for a way to sell some files from my Web Server to clients. I have created my own HTTP server and I have experience programming in HTML, CSS, and a little bit of JavaScript. While I have seen tutorials on creating download links with HTML 5, I ...

Tips for triggering a click event on a hyperlink using a JavaScript function within the Nightmare library

I'm trying to figure out how to click a button using Nightmare with specific attributes. <a class="auth_button leftbtn" href="javascript:SubmitAuthCode( 'enter a friendly name here' );"> <h3>Submit</h3> < ...

Error: Call stack size limit reached in Template Literal Type

I encountered an error that says: ERROR in RangeError: Maximum call stack size exceeded at getResolvedBaseConstraint (/project/node_modules/typescript/lib/typescript.js:53262:43) at getBaseConstraintOfType (/project/node_modules/typescript/lib/type ...

React component fails to display content following execution of Jquery Ajax request

Utilizing a basic jQuery ajax function to retrieve inline HTML code from an API $.ajax({ url: url, headers: { 'Accept': 'application/javascript' }, dataType: 'html', beforeSend: function(){ $('.load-mor ...

unable to see the follow button in the website's Vue component

I am struggling to locate the button on my website Let's take a look at the FollowButton.Vue code below: <template> <div> <button class="btn btn-primary ml-4">Follow Me Now</button> </div> </temp ...

Array values remain unchanged after forEach method execution

availableButtons.forEach(function(part, index) { console.log(this[index].title) // this[index].title = intl.formatMessage(this[index].title); }, availableButtons) The snippet above demonstrates looping through an array of available buttons to pr ...

I am receiving all NFT IDs when I should only be getting the ones that are associated with the current account

I am facing an issue where I am receiving all NFTs token IDs instead of just the one that belongs to the current account. The code snippet causing this problem is as follows: const { enableWeb3, account, isWeb3Enabled, Moralis, deactivateWeb3 } = useMorali ...