Vue:根元素内容和内容分发槽

u.d*_*dev 5 vue.js vuejs2

templateVue构造函数选项的Vue文档中指出,除非除非模板中存在内容分发槽,否则不会显示根元素的内容。但是,当尝试编写如下内容时:

new Vue({
  el: '#app',
  template: `
    <div>
      <h1>App title</h1>
      <slot></slot>
    </div>
  `
});
Run Code Online (Sandbox Code Playgroud)
<html>

<body>
  <div id="app">
    App content
  </div>
  <script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
</body>

</html>
Run Code Online (Sandbox Code Playgroud)

不包括根元素中的内容,正确的方法是什么?

或在创建vue实例时以编程方式注入其他内容的建议方法是什么?

acd*_*ior 8

在某些方面,根的行为与常规组件不同:您不能传递props,也不能<slot>在其模板中直接使用 s (相关:vue/#4485)。

看一下当前的源代码:它们$slots是由函数 解析的,并且在根组件上调用它的resolveSlotsis,因此没有解析槽。在那之后并不重要,但实际上,根组件永远不会填充其.resolveSlots$options._renderChildrenundefined$options._renderChildren

据说<slot>处理逻辑使事情变得有点复杂,因此这可能是一个设计决策。

替代解决方案

通常用于处理您所要求的内容的模式只是将内容包装在另一个组件(例如<app>)组件中,然后从那里开始。

Vue.component('app', {
  template: `<div>
    <h2>I'm the &lt;app&gt; component title</h2>
    <slot>app slot default text</slot>
  </div>`
});
new Vue({
  el: '#app'
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
<div id="app">
  <app>
    I'm the contents of app's template and was declared in root
  </app>
</div>
Run Code Online (Sandbox Code Playgroud)

请参阅下面的演示中this.$slots如何不填充 root,即使它有s。<slot>

Vue.component('app', {
  template: `<div>
    <h2>I'm the &lt;app&gt; component title</h2>
    <slot>app slot default text</slot>
  </div>`,
  created() {
    console.log("<app>'s VDOM children (LENGTH): ", this.$options._renderChildren.length);
    console.log("<app>'s slots (LENGTH): ", this.$slots.default.length);
  }
});
new Vue({
  el: '#app',
  created() {
    console.log("root's VDOM children: ", this.$options._renderChildren);
    console.log("root's slots: ", this.$slots);
  }
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/vue@2.5.13/dist/vue.min.js"></script>
<div id="app">
  <app>
    I'm the contents of app's template
  </app>

  <slot>root's slot's default content, won't make it into $slots, check the console</slot>
</div>
Run Code Online (Sandbox Code Playgroud)