Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 823
Coffee Bite Avatar asked Nov 15 '17 01:11

Coffee Bite


2 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>
like image 156
Bert Avatar answered Sep 22 '22 22:09

Bert


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.

like image 34
Elizabeth Fine Avatar answered Sep 23 '22 22:09

Elizabeth Fine