编写 v1 嵌套 Web 组件

Composing v1 nested web components

我是网络组件的新手。由于 webcomponents v1 可用,我从那里开始。我已经阅读了网络上关于它们的各种帖子。我对正确地组合它们特别感兴趣。我已经阅读了插槽并让它们工作,尽管我的努力并没有导致插槽网络组件按我预期的方式工作。

如果我像这样编写嵌套的 Web 组件,nested/slotted Web 组件中的 DOM 不会插入到父组件的插槽中:

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

这是父网络组件 HTML:

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

由于每个 web 组件(父和子)都是独立编写的,所以我一直在创建它们:

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

生成的 DOM 包括 2 个影子根。我尝试编写 child/slotted 没有影子 dom 的元素,这也不会导致父影子 dom 承载子元素。

那么,编写 v1 嵌套 webcomponents 的正确方法是什么?

首先,你必须使用

然后对 attachShadow() 的调用将自动将新影子 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() 为使用 <slot> 标签插入的元素设置样式。