LoginSignup
2
2

More than 3 years have passed since last update.

Web Components触ってみた

Posted at

Web Componentsとは

再利用可能な部品を作成するための技術。今回はその要素であるCustom ElementsとShadow DOMを触ってみます。

Custom Elements

独自の要素を作成できる。

ElementA.js
class ElementA extends HTMLElement {
  constructor() {
    super();
    this.innerHTML = `
      <style>
        div { color: red }
      </style>
      <div>Hello</div>`
  }
}

customElements.define('element-a', ElementA);

HTMLElementを継承したclassを定義し、customElements.defineで要素を定義することでHTMLで<element-a></element-a>のように呼ぶことができます。

Shadow DOM

要素をカプセル化できます。カプセル化することによって他のstyleの影響をうけなくなります。

ElementB.js
class ElementB extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'});
    this.shadowRoot.innerHTML = `
      <style>
        div { color: blue }
      </style>
      <div>Hello</div>`
  }
}

customElements.define('element-b', ElementB);

this.attachShadowを呼び出すことでShadow DOMを作成できます。

定義した要素を使う

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Web Components</title>
    <script type="module" src="./ElementA.js"></script>
    <script type="module" src="./ElementB.js"></script>
</head>
<body>
    <element-a></element-a>
    <element-b></element-b>
</body>
</html>

このようにして定義した要素を呼び出します。

screenshot.png

所感

Reactなどのライブラリを使用せずに、素のJavaScriptで再利用可能な部品を作成できるところがいいですね。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2