【问题标题】:Webcomponents based on <table>. Slot out of flow基于 <table> 的 Web 组件。插槽流出
【发布时间】:2020-09-29 16:17:28
【问题描述】:

我正在尝试使用基于 TABLE 的“Web 组件”创建数据网格。我在 TBODY 中使用插槽来附加新项目。但是 TR 行呈现出 TBODY。我不明白这种行为。 shadowDom disallow 使用 TABLE 和 TR 元素,可能是这个原因,但是使用 HTMLElement.appendChild() 也不起作用

<html>
<head>
<script type="module"> 
    class DataGrid extends HTMLElement {
      TEMPLATE_ID = '#data-grid';
      constructor() {
        super();
        this._records = [];
      }
      connectedCallback() {
        let shadow = this.attachShadow({mode: 'open'});
        this._render(shadow);
      }

      _render(shadow){
        let tmpl = document.querySelector(this.TEMPLATE_ID);
        shadow.appendChild(tmpl.content.cloneNode(true));
        //this.appendChild(tmpl.content.cloneNode(true)); //
      }
    }

    customElements.define('data-grid', DataGrid);
</script>
</head>
<body>
    <template id="data-grid">
    <table border="1">
      <thead>
        <tr>
          <th>id</th>
          <th>time</th>
          <th>voltage</th>
        <tr>
      </thead>
      <tbody>
        <slot></slot>
      <tbody>
    </table>
    </template>

    <data-grid>
      <!-- need replaced to component
<grid-row time="" voltage=""> 
 -->
      <tr>
        <td>1</td>
        <td>123123123120</td>
        <td>12.0</td>
      </tr>
      <tr>
        <td>2</td>
        <td>123123133324</td>
        <td>12.1</td>
      </tr>
      <tr>
        <td>1</td>
        <td>123123122330</td>
        <td>12.2</td>
      </tr>
    </data-grid>

 </body>

【问题讨论】:

    标签: javascript html web-component


    【解决方案1】:

    来自 MDN 上的 &lt;TR&gt; 文档:

    https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr

    允许的父母

    &lt;table&gt;(仅当表没有子 &lt;tbody&gt; 元素时,甚至 然后仅在任何&lt;caption&gt;&lt;colgroup&gt;&lt;thead&gt; 之后 元素);否则,父级必须是 &lt;thead&gt;&lt;tbody&gt;&lt;tfoot&gt;

    所以

    <data-grid>
      <tr>
    

    不是有效的 HTML

    移动(无效)lightDOM&lt;table&gt; inside &lt;data-grid&gt; shadowDOM

    注意: attachShadow() setsreturns this.shadowRoot 免费
    无需创建自己的shadow 变量。

    伪代码:

    const table = this.shadowRoot.querySelector("TABLE");
    this.querySelectorAll("TR").forEach(table.appendChild);
    
    

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 2019-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多