简体   繁体   中英

The Javascript function i created to automate web component creation doesn't work. What's wrong?

I created a JavaScript function that is meant to repeat the code that is used to create a new web component. But for some reason, it is not recognized by the browser. I'm not sure what went wrong her. Below is the code: _.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",
    <div>
        <h1>Title</h1>
        <nav>
            <a href="/">Home</a>
            <a href="about">About</a>
            <a href="contact">Contact us</a>
        </nav>
    </div>
)

index.html (I'm only showing the relevant part):

<body>
    <div style="width: clamp(0px,1000px,90%);">
        <component-header></component-header>
        <h2>Topic Name</h2>
    </div>
    <script src="./components/toolTip.js"></script>
    <script src="./components/header.js"></script>
</body>

How do I make it render the component in the web page as is it supposed to?

Your code looks fine at first sight.

Add plenty of console.log( ) statements to see what does not execute.

BTW

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);

can be written as:

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

But why use shadowDOM at all?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM