今更WebComponentsの触り
わりとガンガンjQueryな、とくにUIライブラリも使っていない。(jQueryUIはあるけど)
いろいろと辛い状況なやつ。
画面追加がある度に、ほぼその画面に合わせてCSSも書きつつ。
レイアウト指示はそこそこ細かく、px単位でたまに指摘される。
そんなのが続くと画面追加があるたびに、HTML、CSS書くのめんどくさい!!!という感情が湧いてくるわけです。
WebComponentsって楽できないのかな・・・がはじまり。
書き方基礎
<hello-world/>
class HelloWorld extends HTMLElement { constructor() { super() const shadowRoot = this.attachShadow({ mode: 'open" }) shadowRoot.innerHTML = `<h1>Hello World</h1>` } } customElements.define('hello-world', HelloWorld)
書き方は意外と簡単ですね。
プロパティ与えたい
React, Vue, Angularなんかを書いていると、コンポーネントにpropsを渡して描画することが多々あります。
似たようなことできないの?って思ったんですが、厳しそうです。
<hello-world data-name="Bob"/>
const HelloWorld extends HTMLElement { constructor() { super() this.myName = this.getAttribute('data-name') ? this.getAttribute('data-name') : '' const shadowRoot = this.attachElement({ mode: 'open' }) shadowRoot.innerHTML = this.template() } template() { return `<h1>Hello ${this.myName}` } } customElements.define('hello-world', HelloWorld)
Attributeでプロパティは渡せるけど、取り出したらこれ文字列ですよね。
無理矢理JSONなんか渡したらいけるのかもしれないけど、そこまでするか・・・?
ちょっとしたステータスで色変えたいよ。とか、そんなレベルで使うのが良いのかなと思いました。
いわゆるJS FW系で扱ってるようなコンポーネントとは似て非なるもの。って感じでしょうか。
まだ詳しくは調べてないけど、間違ってたらすいません。