Coffee Bite
Coffee Bite

Reputation: 5164

Get inner html of the component as a variable in vuejs 2

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?

Upvotes: 7

Views: 21590

Answers (2)

Elizabeth Fine
Elizabeth Fine

Reputation: 150

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.

Upvotes: 3

Bert
Bert

Reputation: 82489

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>

Upvotes: 7

Related Questions