我是Web组件的新手。由于可以使用v1的webcomponents,因此我从这里开始。我已经在网上阅读了有关它们的各种帖子。我对正确地构成它们特别感兴趣。我已经阅读了有关插槽并使其工作的信息,尽管我的努力并未使插槽化的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.innterHTML = `HTML markup`
}
})
生成的DOM包括2个阴影根。我尝试编写不带影子dom的子代/插槽元素,这也不会导致托管子代的父影子dom。
那么,什么是组成v1嵌套Web组件的正确方法呢?
最佳答案
首先,您必须使用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()
样式化使用<slot>
标签插入的元素。 关于javascript - 组成v1嵌套的Web组件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38976819/