2016-08-16 20 views
6

Webコンポーネントを初めて使用しています。 v1のWebコンポーネントが利用可能なので、そこから始めます。私はそれらについてウェブ上で様々な投稿を読んだ。私は特にそれらを正しく構成することに興味があります。私はスロットについて読んだことがありますが、私の努力は、私が期待した通りに動作するスロットのあるWebコンポーネントをもたらさなかったものの、動作させることができました。v1ネストされたWebコンポーネントの作成

私はこのようなネストされたWebコンポーネントを構成している場合は、溝付き/ネストされたwebcomponentからDOMが親のスロットに挿入されません。

<parent-component> 
 
    <child-component slot="child"></child-component> 
 
</parent-component>

をそしてここで、親のwebcomponent HTML:

<div id="civ"> 
 
    <style> 
 
    </style> 
 
    <slot id="slot1" name="child"></slot> 
 
</div>

各webcomponent(親と子)が独立していると書かれているので、私はそれらを作成されています:

customElements.define('component-name', class extends HTMLElement { 
 
    constructor() { 
 
    super(); 
 
    this.shadowRoot = this.attachShadow({mode: 'open'}); 
 
    this.shadowRoot.innterHTML = `HTML markup` 
 
    } 
 
})

結果のDOMは2つの影の根を含んでいます。私はshadow domなしでchild/slotted要素を記述しようとしましたが、これは親shadow domが子をホストすることにはなりません。

したがって、v1ネストされたWebコンポーネントを作成する正しい方法は何ですか?

答えて

4

まず、a browser that implements Shadow DOM and Custom Elements v1を使用する必要があります。

attachShadow()を呼び出すと、新しいシャドウDOMがread-onlyプロパティshadowRootに自動的に割り当てられます。

Shadow DOMのinnerHTMLにHTMLコードを追加することはできますが、代わりに<template>contentプロパティを使用することをおすすめします。

その後ネストが自然である:スタイルに

  • :hostは、カスタム要素自体のスタイルを、そして
  • ::slotted()<style>タグで

    customElements.define('parent-component', class extends HTMLElement { 
     
        constructor() { 
     
         super() 
     
         this.attachShadow({mode: 'open'}) 
     
         this.shadowRoot.appendChild(parent1.content.cloneNode(true)) 
     
        } 
     
    }) 
     
          
     
    customElements.define('child-component', class extends HTMLElement { 
     
        constructor() { 
     
         super() 
     
         var sh = this.attachShadow({mode: 'open'}) 
     
         sh.appendChild(child1.content.cloneNode(true)) 
     
        } 
     
    })
    <parent-component> 
     
        <child-component slot="child"> 
     
         <span>Hello</span> 
     
        </child-component> 
     
    </parent-component> 
     
    
     
    
     
    <template id="parent1"> 
     
        <style> 
     
         :host { background: lightblue ; display: inline-block } 
     
         ::slotted([slot=child]) { background: lightyellow } 
     
        </style> 
     
        <h4>(parent)</h4> 
     
        <p>Slotted child: 
     
         <slot name="child"></slot> 
     
        </p> 
     
    </template>  
     
    
     
    <template id="child1"> 
     
        <style> 
     
         :host { display: inline-block } 
     
         ::slotted(span) { background: pink } 
     
        </style> 
     
        <h5>(child)</h5> 
     
        <span>Nested slot: <slot></slot></span> 
     
    </template>

    、使用要素インサイドdに<slot>タグを付けてください。

関連する問題