获取 Vue 插槽的渲染 HTML 内容作为变量

Dja*_*ave 6 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);
  }
});
Run Code Online (Sandbox Code Playgroud)

这会记录以下内容:

[fo, fo, fo, fo, fo, fo, fo]
Run Code Online (Sandbox Code Playgroud)

每个fo包含如下内容:

{tag: undefined, data: undefined, children: undefined, text: " ", elm: text, …}
Run Code Online (Sandbox Code Playgroud)

console.log会怎么样:

<p>Hi there</p><p>Hi <span>heloo</span></p><p>Hi there</p><p>Hi there</p>
Run Code Online (Sandbox Code Playgroud)

为此,您可以假设没有嵌套组件。

Jac*_*Goh 5

将获得innerHTMLthis.$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>
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

  • 更简单、更稳定:将 `ref="slotWrapper"` 放在元素上并使用 `this.$refs.slotWrapper.innerHTML`。 (2认同)