Answer a question

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?

Answers

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>
Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐