示例工程 30-web-components-types

30-web-components-types/01-typed-element/src/main.ts

typescript · 1.1 KB

运行:30 · typed-element

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

export class XCounter extends HTMLElement {
  #count = 0;
 
  connectedCallback(): void {
    if (this.shadowRoot === null) {
      this.attachShadow({ mode: 'open' });
    }
    this.#render();
  }
 
  increment(): void {
    this.#count += 1;
    this.#render();
  }
 
  get count(): number {
    return this.#count;
  }
 
  #render(): void {
    const root = this.shadowRoot;
    if (root === null) return;
    root.innerHTML = `<button>${this.#count}</button>`;
  }
}
 
declare global {
  interface HTMLElementTagNameMap {
    'x-counter': XCounter;
  }
}
 
export function defineCounter(): void {
  if (typeof customElements === 'undefined') throw new Error('本示例需要浏览器环境');
  if (!customElements.get('x-counter')) {
    customElements.define('x-counter', XCounter);
  }
}
 
export function run(log: (msg: string) => void = console.log): string[] {
  defineCounter();
  const element = document.createElement('x-counter');
  document.body.append(element);
  element.increment();
  element.increment();
  const lines = [String(element.count)];
  for (const line of lines) {
    log(line);
  }
  return lines;
}