Shobi
Shobi

Reputation: 11451

How to get the compiled html content of a component in vuejs

I have a component like this <AgentCard :agent="agent" />, where agent is an object with properties like FirstName, LastName, Recent Orders etc...

Now I need to show this component inside a Google Maps InfoBox. The infoWindow.setContent() method (the Google Maps API to display the popup info window) accepts only an HTML string, so I am trying to render the <AgentCard> manually, get the HTML content of the rendered component, and pass it on to the setContent() method.

I tried Vue.compile('<AgentCard :agent="agent" />').render(), but this doesnt work. How do I render a Vue component manually, and get its HTML content?

Upvotes: 5

Views: 3515

Answers (2)

Ernane Luis
Ernane Luis

Reputation: 361

on Vue 3:

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

Upvotes: 2

tony19
tony19

Reputation: 138216

One solution is to create a new Vue instance with only the target component, $mount it, and then get the outerHTML of its $el (root element):

<script src="https://unpkg.com/[email protected]/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>

Upvotes: 2

Related Questions