【问题标题】:Composing v1 nested web components组合 v1 嵌套 Web 组件
【发布时间】:2016-12-22 22:36:25
【问题描述】:

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

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

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

这是父 Web 组件 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 个影子根。我尝试编写没有 shadow dom 的子元素/开槽元素,这也不会导致父 shadow dom 托管子元素。

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

【问题讨论】:

    标签: javascript web-component shadow-dom custom-element


    【解决方案1】:

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

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

    您可以将 HTML 代码附加到 Shadow DOM 的 innerHTML,但我建议改用 &lt;template&gt;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>

    &lt;style&gt; 标签中,使用:

    • :host 设置自定义元素本身的样式,以及
    • ::slotted() 为使用&lt;slot&gt; 标签插入的元素设置样式。

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 2017-06-15
      • 2018-06-29
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 2022-09-27
      • 2017-07-26
      • 2017-12-31
      相关资源
      最近更新 更多