2016-08-16 99 views
6

我是webcomponents的新手。由于webcomponents v1是可用的,我从那里开始。我已经阅读了关于他们网络的各种帖子。我特别感兴趣的是正确编写它们。我已经阅读了有关插槽并让它们工作,尽管我的努力并没有导致按我期望的方式工作的插槽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阴影根。我试图编写没有阴影dom的子/开槽元素,这也不会导致父主管dom托管孩子。

那么,构建v1嵌套webcomponents的正确方法是什么?

回答

4

首先,您必须使用a browser that implements Shadow DOM and Custom Elements v1

然后调用attachShadow()将自动将新的Shadow DOM分配给read-only属性shadowRoot

您可以将HTML代码附加到Shadow DOM的innerHTML,但我建议使用<template>content属性代替。

然后嵌套是很自然的:

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>

<style>标签,使用:

  • :host的风格自定义元素本身,
  • ::slotted()款式元素插入d与<slot>标签。