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

Viewed 1036

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?

1 Answers

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/vue@2.6.12/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>

Related