我已经开始了vue web组件库的开发。我的团队成员要求通过web组件上的HTML属性删除默认样式。我知道我可以在模板元素上使用CSS类绑定,但是,我想知道是否有一种方法可以有条件地包含样式标记本身,这样我就不需要为了包含基本样式而更改类名称。
组件结构示例
<template>
<section class="default-class" />
</template>
<script>
export default {
props: {
useDefault: Boolean
}
}
</script>
<style>
// Default styles included here
// Ideally the style tag or it's content could be included based off useDefault prop
</style>潜在的实现
<web-component use-default="false"></web-component>发布于 2021-11-01 18:59:08
当我读到您的问题时,您希望同时影响全局DOM和shadowDOM的<style>
一种方法是将这些<style>元素克隆到shadowDOM中
但也许::parts更适合您;请参阅:https://meowni.ca/posts/part-theme-explainer/
customElements.define("web-component", class extends HTMLElement {
constructor() {
super()
.attachShadow({mode:"open"})
.innerHTML = "<div>Inside Web Component</div>";
}
connectedCallback() {
// get all styles from global DOM and clone them inside the Web Component
let includeStyles = this.getAttribute("clone-styles");
let globalStyles = document.querySelectorAll(`[${includeStyles}]`);
let clonedStyles = [...globalStyles].map(style => style.cloneNode(true));
this.shadowRoot.prepend(...clonedStyles);
}
});<style mystyles>
div {
background: gold
}
</style>
<style mystyles>
div {
color: blue
}
</style>
<div>I am Global</div>
<web-component clone-styles="mystyles"></web-component>
https://stackoverflow.com/questions/69799730
复制相似问题