Say I have a vuejs component called child-component which is added to a parent component as follows.
<child-component>
  <div>Hello</div>
</child-component>
N.B. this is not the template of the child component. This is how the child component is added to the parent.
How can I get the innerHTML, i.e. <div>Hello</div> in the child component as a string?
Inside the component, child-component, the HTML would be available in the mounted lifecycle handler as this.$el.innerHTML. The parsed vnodes would be available from this.$slots.default.
console.clear()
Vue.component("child-component",{
  template: `<div><slot/></div>`,
  mounted(){
    console.log("HTML", this.$el.innerHTML)
  }
})
new Vue({
  el: "#app"
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <child-component>
    <div>Hello</div>
  </child-component>
</div>
You could look at using Vue Child Component Refs. That will let you access the child component's innerHTML from the parent component.
Just add a ref attribute to your child component. It can be anything you choose:
<child-component ref="mychildcomponent">
   <div>Hello</div>
</child-component>
Then in the parent methods, you can do something like:
let childEl = this.$refs.mychildcomponent
That will set childEl the entire child component that you've referenced. To get the innerHTML youd just have to go a little further, and do something like this:
let childEl = this.$refs.mychildcomponent.$el.innerHTML
That should give you a string of the child component's innerHTML.
This might help: https://v2.vuejs.org/v2/guide/components.html#Child-Component-Refs
Alternatively if you want to get it from the child component itself, just do the following within a method:
let componentHTML = this.$el.innerHTML
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With