Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

javascript - Composing v1 nested web components

I'm new to webcomponents. Since v1 of webcomponents is available, I'm starting there. I have read various posts around the web about them. I'm particularly interested in composing them correctly. I have read about slots and have them working, although my efforts have not resulted in slotted webcomponents that work the way I expected.

If I have compose nested web components like this, the DOM from the nested/slotted webcomponent does not get inserted in the slot of the parent:

<parent-component>
  <child-component slot="child"></child-component>
</parent-component>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, you must use a browser that implements Shadow DOM and Custom Elements v1.

Then the call to attachShadow() will assign the new Shadow DOM automatically to the read-only property shadowRoot.

You can append the HTML code to the Shadow DOM's innerHTML but I'd recommend to use a <template>'s content property instead.

Then nesting is natural:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...