将Vue槽的HTML内容呈现为变量

时间:2018-05-02 11:06:41

标签: vue.js vuejs2

我知道你可以这样做:

<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);
  }
});

记录以下内容:

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

每个fo包含以下内容:

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

我将如何console.log

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

出于此目的,您可以假设没有嵌套组件。

1 个答案:

答案 0 :(得分:3)

innerHTML获取this.$el是否适合您?

演示: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"
});