gpt4 book ai didi

javascript - 网络组件 : how to get the resolved value of a slot in shadow DOM?

转载 作者:行者123 更新时间:2023-11-30 23:54:57 25 4
gpt4 key购买 nike

我有一个 Web 组件,我想调整其插槽的值。

不幸的是,我无法从中获得解析值。

我怎样才能做到这一点?

const template = document.createElement('template');
template.innerHTML = `
<p><slot></slot></p>
`;

class MyComp extends HTMLElement {
constructor() {
super();
this.root = this.attachShadow({mode: 'open'});
this.root.appendChild(template.content.cloneNode(true));
}

connectedCallback() {
const slot = this.shadowRoot.querySelector('slot');
console.log('VALUE:', slot.innerText); // always empty
}
}

customElements.define('my-comp', MyComp);
<my-comp>abc</my-comp>

最佳答案

您可以分配一个 EventListener 来监视 SLOT 更改

MDN 文档

customElements.define('my-element', class extends HTMLElement {
constructor() {
super();
this.attachShadow({
mode: 'open'
}).appendChild(document.getElementById(this.nodeName).content.cloneNode(true));
}

connectedCallback() {
this.listeners = [...this.shadowRoot.querySelectorAll("SLOT")].map(slot => {
let name = "slotchange";
let func = (evt) => {
let nodes = slot.assignedNodes();
console.log(`Slot ${slot.name} changed to ${nodes[0].outerHTML}`)
}
slot.addEventListener(name, func);
return () => slot.removeEventListener(name, func); // return cleanup function!!!
})
}
disconnectedCallback() {
this.listeners.forEach(removeFunc => removeFunc());
}
});
<template id="MY-ELEMENT">
<style>
::slotted(*) {
background: yellow;
margin: 0;
}

::slotted(span) {
color: red;
}

</style>
<b>
<slot name=title></slot>
</b>
<slot name=content></slot>
</template>

<my-element>
<span slot="title">Hello World</span>
<p slot="content">What a wonderful day!</p>
</my-element>
<my-element>
<span slot="title">Hello Tomorrow</span>
<p slot="content">What will you bring?</p>
</my-element>

关于javascript - 网络组件 : how to get the resolved value of a slot in shadow DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61122069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com