如何从其插槽元素中引用插槽元素?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (6)

我有一个名为'stack-item'的组件,它有一个插槽,它的html看起来像这样

<div>
<div>1<div>
<div class='slot-style'><slot></slot></div>
</div>

我像这样使用过这个组件

<stack-item>
   <another-component></another-component>
</stack-item>

从'another-component'我如何得到class ='slot-style'的元素引用来计算槽宽和其他属性?

我写了一个解决方法

let slotElement =this.shadowRoot.host.parentElement.shadowRoot.querySelector('slot').parentElement;

但有没有一个干净的方法来实现这一目标?

提问于
用户回答回答于

I don't know if this can be considered dramatically simpler, but the scenario you give indicates that you already know the host component is stack-item and that component has a slot wrapper with the class name 'slot-style'. Given that you can obtain a reference like this (this works from within the component as well as the host document):

let slotElement = document.querySelector("stack-item").shadowRoot.querySelector(".slot-style");
//display width
console.log(slotElement.clientWidth);

扫码关注云+社区

领取腾讯云代金券