首页 > 解决方案 > 为什么我不能将我的设置器用于带有模板的纯 JS 中的自定义元素?

问题描述

我对 Web 组件还很陌生,并且一直在试图弄清楚这些东西是如何工作的。在执行创建模板的推荐过程时,然后将其克隆到我的shadowRoot我可以在我的 chrome 元素中看到它们,但不能在网页本身上看到它们。

例如:

import './components/ingredients/ingredients-table';

const template = document.createElement('template');
template.innerHTML = `
    <h3>Add some ingredients</h3>
    <ingredients-table id="hehe"></ingredients-table>

`

class App extends HTMLElement {
    constructor() {
        super();
        this._shadowRoot = this.attachShadow({ mode: 'open' });
        this._shadowRoot.appendChild(template.content.cloneNode(true));
    }

    connectedCallback() {
        console.log(this._shadowRoot.querySelector('ingredients-table').id)
        this._shadowRoot.querySelector('ingredients-table').ingredients = [
            "1 tbsp, cinnamon extract",
            "2 tbsp, cinnamon extract",
            "3 tbsp, cinnamon extract",
            "4 tbsp, cinnamon extract",
            "5 tbsp, cinnamon extract",
            "6 tbsp, cinnamon extract",
        ];
    }
}

window.customElements.define('main-app', App);

window.addEventListener('load', () => {
    const main = document.querySelector('main');
    const app = document.createElement('main-app');
    main.appendChild(app);

});

这表明了 这一点,这反过来意味着<ingredients-table>的 set 功能不起作用

但是当我将构造函数行更改this._shadowRoot.appendChild(template.content.cloneNode(true));

this._shadowRoot.innerHTML = `
    <h3>Add some ingredients</h3>
    <ingredients-table id="hehe"></ingredients-table>
`

我明白

有人可以澄清这到底是如何工作的吗?谢谢

这是一个代码笔: https ://codepen.io/aishmitkhurana/pen/wvaKWBL ?editors=0010

标签: javascriptweb-componentshadow-dom

解决方案


您的错误是(简单)错字

挖掘完你的 CodePen
https://codepen.io/aishmitkhurana/pen/wvaKWBL?editors=0010

你的代码:

const template = document.createElement('template');
template.innerHTML =  `
    <h3>Add some ingredients</h3>
    <ingredients-table></ingredients-table>
    <recipe-steps></recipe-steps>`

...more code...

const template2 = document.createElement('template');
template  <--TYPO    .innerHTML = `
    <table>
        <ingredients-list></ingredients-list>
        <tr>
            <input
                id="ingredients-input"
                placeholder="e.g. 3/4 tbsp cinnamon powder"
            >
        </tr>
    </table>`

您正在将第二个 HTML分配给第一个 模板

您的 F12 开发控制台清楚地表明:

对于该行:

this._shadowRoot.querySelector('ingredients-table').ingredients =

因为EMPTY模板中没有 <ingredients-table> 元素2


推荐阅读