How to separate web components to individual files and load them?

后端 未结 1 1190
后悔当初
后悔当初 2020-11-27 17:42

I have a web component x-counter, which is in a single file.

const template = document.createElement(\'template\');
template.innerHTML = `
  <         


        
相关标签:
1条回答
  • 2020-11-27 18:06

    In the main file, use <script> to load the Javascript file x-counter.js.

    In the Javascript file, use fetch() to load the HTML code x-counter.html.

    In the HTML file, use <link rel="stylesheet"> to load the CSS file x-counter.css.

    CSS file : x-counter.css

    button, p {
        display: inline-block;
        color: dodgerblue;
    }
    

    HTML file : x-counter.html

    <link rel="stylesheet" href="x-counter.css">
    <button aria-label="decrement">-</button>
        <p>0</p>
    <button aria-label="increment">+</button>
    

    Javascript file : x-counter.js

    fetch("x-counter.html")
        .then(stream => stream.text())
        .then(text => define(text));
    
    function define(html) {
        class XCounter extends HTMLElement {
            set value(value) {
                this._value = value;
                this.valueElement.innerText = this._value;
            }
    
            get value() {
                return this._value;
            }
    
            constructor() {
                super();
                this._value = 0;
    
                var shadow = this.attachShadow({mode: 'open'});
                shadow.innerHTML = html;
    
                this.valueElement = shadow.querySelector('p');
                var incrementButton = shadow.querySelectorAll('button')[1];
                var decrementButton = shadow.querySelectorAll('button')[0];
    
                incrementButton.onclick = () => this.value++;
                decrementButton.onclick = () => this.value--;
            }
        }
    
        customElements.define('x-counter', XCounter);
    }
    

    Main file : index.html

    <html>
    <head>
        <!-- ... -->
        <script src="x-counter.js"></script>
    </head>
    <body>
        <x-counter></x-counter>
    </body>
    </html>
    
    0 讨论(0)
提交回复
热议问题