首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单个文件组件中的Vue条件样式标记

单个文件组件中的Vue条件样式标记
EN

Stack Overflow用户
提问于 2021-11-01 16:18:27
回答 1查看 64关注 0票数 0

我已经开始了vue web组件库的开发。我的团队成员要求通过web组件上的HTML属性删除默认样式。我知道我可以在模板元素上使用CSS类绑定,但是,我想知道是否有一种方法可以有条件地包含样式标记本身,这样我就不需要为了包含基本样式而更改类名称。

组件结构示例

代码语言:javascript
复制
    <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>

潜在的实现

代码语言:javascript
复制
    <web-component use-default="false"></web-component>
EN

回答 1

Stack Overflow用户

发布于 2021-11-01 18:59:08

当我读到您的问题时,您希望同时影响全局DOM和shadowDOM的<style>

一种方法是将这些<style>元素克隆到shadowDOM中

但也许::parts更适合您;请参阅:https://meowni.ca/posts/part-theme-explainer/

代码语言:javascript
复制
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);
  }
});
代码语言:javascript
复制
<style mystyles>
  div {
    background: gold
  }
</style>
<style mystyles>
  div {
    color: blue
  }
</style>

<div>I am Global</div>
<web-component clone-styles="mystyles"></web-component>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69799730

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档