如何将Web组件分离为单个文件并加载它们?

时间:2019-03-09 17:33:35

标签: javascript html templates web-component separation-of-concerns

我有一个Web组件x-counter,位于单个文件中。

const template = document.createElement('template');
template.innerHTML = `
  <style>
    button, p {
      display: inline-block;
    }
  </style>
  <button aria-label="decrement">-</button>
    <p>0</p>
  <button aria-label="increment">+</button>
`;

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;

    this.root = this.attachShadow({ mode: 'open' });
    this.root.appendChild(template.content.cloneNode(true));

    this.valueElement = this.root.querySelector('p');
    this.incrementButton = this.root.querySelectorAll('button')[1];
    this.decrementButton = this.root.querySelectorAll('button')[0];

    this.incrementButton
      .addEventListener('click', (e) => this.value++);

    this.decrementButton
      .addEventListener('click', (e) => this.value--);
  }
}

customElements.define('x-counter', XCounter);

此处,模板定义为使用JavaScript,并且html内容作为内联字符串添加。有没有办法将模板分离到x-counter.html文件中,用CSS表示x-counter.css,将相应的JavaScript代码分离到xcounter.js中并将它们加载到index.html中?

每个示例中,我的查询都有混合的Web组件。我想分离关注点,但是我不确定如何使用组件来实现。您能否提供示例代码?谢谢。

1 个答案:

答案 0 :(得分:2)

在主文件中,使用telegraf加载Javascript文件<script>

在Javascript文件中,使用x-counter.js加载HTML代码fetch()

在HTML文件中,使用x-counter.html加载CSS文件<link rel="stylesheet">

CSS文件:x-counter.css

x-counter.css

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

x-counter.html

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

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

index.html