如何将 Web 组件分离到单个文件并加载它们? [英] How to separate web components to individual files and load them?

查看:21
本文介绍了如何将 Web 组件分离到单个文件并加载它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Web 组件 x-counter,它在一个文件中.

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

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 中?

Here the template is defined as using JavaScript and html contents are added as inline string. Is there a way to separate template to an x-counter.html file, css to say, x-counter.css and corresponding JavaScript code to xcounter.js and load them in index.html?

我查找的每个示例都混合了 Web 组件.我想要关注点分离,但我不确定如何使用组件来做到这一点.你能提供一个示例代码吗?谢谢.

Every example I lookup has web components mixed. I would like to have separation of concerns, but I am not sure how to do that with components. Could you provide a sample code? Thanks.

推荐答案

在主文件中,使用

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆