我为自动创建 Web 组件而创建的 Javascript 函数不起作用。怎么了?

分享于2022年07月17日 components html javascript web-component 问答
【问题标题】:我为自动创建 Web 组件而创建的 Javascript 函数不起作用。怎么了?(The Javascript function i created to automate web component creation doesn't work. What's wrong?)
【发布时间】:2022-01-26 00:44:39
【问题描述】:

我创建了一个 JavaScript 函数,旨在重复用于创建新 Web 组件的代码。但是由于某种原因,浏览器无法识别它。我不确定她出了什么问题。下面是代码: _.js:

export const createComponent = (componentName, htmlCode) => {
    const template = document.createElement("template");
    template.innerHTML = `${htmlCode}`;

    class componentClass extends HTMLElement {
        constructor() {
            super();
            this.attachShadow({ mode: "open" }); // access shadow DOM via shadow root        
            this.shadowRoot.appendChild(template.content.cloneNode(true));
        }
    };

    window.customElements.define(componentName, componentClass);
}

header.js:

import { createComponent } from "./_"

createComponent(
    "component-header",
    
)

index.html(我只展示相关部分):


    

Topic Name

如何让它按原样呈现网页中的组件?

  • 试试 template.innerHTML = htmlCode 。如果您在问题编辑器中单击 <> ,您可以在页面的此处运行此代码,以便其他人能够在开发工具中进行调试
  • @charlietfl 如果您将两个 js 文件中的代码都包含在一个 js 文件中,则它可以工作,但我似乎无法导入它。
  • 您不需要导入任何内容,因为您没有为脚本标签使用模块类型并确保它们的顺序正确

【解决方案1】:

您的代码乍一看还不错。

添加大量 console.log( ) 语句以查看哪些不执行。

顺便说一句

const template = document.createElement("template");
    template.innerHTML = `${htmlCode}`;

    class componentClass extends HTMLElement {
        constructor() {
            super();
            this.attachShadow({ mode: "open" }); // access shadow DOM via shadow root        
            this.shadowRoot.appendChild(template.content.cloneNode(true));
        }
    };

    window.customElements.define(componentName, componentClass);

可以写成:

customElements.define(componentName, class extends HTMLElement {
    constructor() {
        super()
          .attachShadow({ mode: "open" })
          .innerHTML = htmlCode;
    }
});

但为什么要使用 shadowDOM?

customElements.define(componentName, class extends HTMLElement {
    connectedCallback() {
        this.innerHTML = htmlCode;
    }
});

  • 这不起作用,但我发现问题不在于我的函数,而是由于某种原因它没有从“_.js”导入到“header.js”。