Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rendered HTML contents of Vue slot as variable

Tags:

vue.js

vuejs2

I know you can do something like this:

<div id="app">
  <div class="container">
    <h1 class="title is-1" v-html="text"></h1>
    <get-slot-contents>
      <p>Hi there</p>
      <p>Hi <span>heloo</span></p>
      <p>Hi there</p>
      <p>Hi there</p>
    </get-slot-contents>
  </div>
</div>

// JS

Vue.component('get-slot-contents', {
  data: function () {
    return {
      html : false
    }
  },
  template: `<div>
    ****
    <slot></slot>
    ****
  </div>`,
  mounted(){
    console.log(this.$slots.default);
  }
});

This logs the following:

[fo, fo, fo, fo, fo, fo, fo]

Each fo containing something like:

{tag: undefined, data: undefined, children: undefined, text: " ", elm: text, …}

How would I console.log something like:

<p>Hi there</p><p>Hi <span>heloo</span></p><p>Hi there</p><p>Hi there</p>

For the purposes of this you can assume there are no nested components.

like image 212
Djave Avatar asked May 02 '18 11:05

Djave


1 Answers

Would getting innerHTML from this.$el works for you?

demo: https://codepen.io/jacobgoh101/pen/vjmzWg?editors=1010

<div id="app">
  <div class="container">
    <h1 class="title is-1"></h1>
    <get-slot-contents>
      <p>Hi there</p>
      <p>Hi <span>heloo</span></p>
      <p>Hi there</p>
      <p>Hi there</p>
    </get-slot-contents>
  </div>
</div>
Vue.component("get-slot-contents", {
  data: function() {
    return {
      html: false
    };
  },
  template: `<div>
    ****
    <div class="slot-wrapper">
        <slot></slot>
    </div>
    ****
  </div>`,
  mounted() {
    console.log(this.$el.getElementsByClassName("slot-wrapper")[0].innerHTML);
  }
});

new Vue({
  el: "#app"
});
like image 110
Jacob Goh Avatar answered Sep 18 '22 21:09

Jacob Goh