【问题标题】:vue.js 2 nested components with inline templating results in error (component must have one child element only)vue.js 2 嵌套组件与内联模板导致错误(组件必须只有一个子元素)
【发布时间】:2021-03-12 06:25:18
【问题描述】:

我正在尝试制作可以为我处理一些表格数据的组件。我认为最好的方法是为表格的每个部分创建一个组件。

所以,我有

Vue.component('my-table', { ... });
Vue.component('my-table-header', { ... });
Vue.component('my-table-header-column', { ... });

在我编写代码时,我的 HTML 首先看起来像这样:

<my-table inline-template>
<table>
  <thead>
    ....
  </thead>
  <tbody>
    ....
  </tbody>
</table>
</my-table>

这工作得很好。

现在我编写了第二个组件(my-table-header)并像这样更改了 HTML:

<my-table inline-template>
<table>
  <my-table-header inline-template>
  <thead>
    ....
  </thead>
  </my-table-header>
  <tbody>
    ....
  </tbody>
</table>
</my-table>

然而,这导致 vue 抱怨“内联模板组件必须只有一个子元素。”

我似乎无法找到一个很好的解释来解释我在这里做错了什么。似乎只是通过使用嵌套组件,我创建了这个问题。

【问题讨论】:

  • 您的my-table 内联组件或您的my-table-header 具有多个根元素。根据您的工作流程,似乎由于后者而发生错误。你确定my-table-header里面没有元素,和thead同级吗?
  • 超级确定。刚刚重新检查(再次)。 &lt;my-table-header inline-template&gt;&lt;thead&gt;&lt;tr&gt;&lt;td v-for&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;/my-table-header&gt;。这就是里面的一切。
  • 我发现这与&lt;table&gt; 元素有关。将我的代码更改为使用 &lt;div&gt; 有效。
  • 您可以尝试将您的表格包裹在一个简单的div 中。

标签: vuejs2 vue-component


【解决方案1】:

问题确实是表格元素太挑剔了,而且东西被扔掉了。

我终于设法让这个与is="component-name" 构造一起工作,如下所示:

<my-table inline-template>
<table>
  <thead is="my-table-header" inline-template>
    <thead>....</thead>
  </thead>
  <tbody>
    ....
  </tbody>
</table>
</my-table>

不要问我为什么要重复 thead 标签。没有它就无法渲染。

【讨论】:

    猜你喜欢
    • 2017-11-12
    • 2018-09-09
    • 2015-12-14
    • 2017-02-02
    • 2017-03-03
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 2013-07-12
    相关资源
    最近更新 更多