在Vue构造函数的template选项的Vue文档中指出,根元素的内容不会显示"unless content distribution slots are present in the template".然而,当你试图写一些东西时,比如:

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

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

</html>

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

或者,在创建vue实例时,建议采用什么方式以编程方式注入额外内容?

推荐答案

在某些方面,root的行为不像常规组件:您可以使用can't pass props,也不能直接在其模板中使用<slot>s(related:vue/#4485).

看看电流源:$slots are resolved byresolveSlots function,在根组件上调用点resolveSlots,它的$options._renderChildrenundefined,因此没有解决任何插槽.这并不重要,但实际上,根组件从未填充其$options._renderChildren.

据说<slot>处理逻辑是complicates things a bit,所以这可能是一个设计决定.

Alternative solution

通常用于处理请求的模式只是将内容包装到另一个组件(比如<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'
});
<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>

在下面的演示中,查看this.$slots如何不为root填充,即使它有<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);
  }
});
<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>

Vue.js相关问答推荐

检测Vue3/Vue-test-utils中的Vuex还原/Mutations

将Vite Vuejs应用部署到Apache服务器

为什么发送 POST API 请求时主体对象没有react ?

v-model 修饰符返回空

已分配计算(computed)属性,但它没有设置器

如果 Vuetify 自动完成没有匹配的结果,则保留输入的文本

Defer推迟执行,直到外部脚本加载到 Vue.js

Eslint Vue 3 解析错误:'>' expected.eslint

使用上传组件而不触发 POST 请求

使用 vee-validate 在 vue js 中进行验证有错误

为什么Vue.js 使用单字标签

我可以在 Vue 实例方法中传播的 mapMutations 中使用this吗?

这是 v-on:change 的正确用法吗?

Vuex 存储数据总是驻留在内存中?

在 nuxt.js 页面中包含外部 javascript 文件

模块构建失败:错误:没有给出解析器和文件路径,无法在 nuxtjs 中推断出解析器

如何通过 Axios 发送文件到 Laravel

如何在 Promise 回调中更新 Vue 应用程序或组件的属性?

Vue.js 3 - 替换/更新react性对象而不会失go react性

为什么不能在 vue 模板中使用窗口?