【问题标题】:Vue conditional style tag in single file component单个文件组件中的Vue条件样式标签
【发布时间】:2021-11-01 16:18:26
【问题描述】:

我已经开始开发一个 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>

【问题讨论】:

  • 没有。您不能有条件地在 SFC 中加载样式标签。
  • 您可以使用这个新功能State-Driven Dynamic CSS
  • 试试这个:

标签: css vue.js web-component


【解决方案1】:

当我读到你的问题时;你想保持&lt;style&gt; 都影响全局 DOM shadowDOM

一种方法是克隆那些&lt;style&gt;元素到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>

【讨论】:

    猜你喜欢
    • 2018-06-02
    • 2021-01-15
    • 2021-09-19
    • 2021-03-19
    • 2012-12-20
    • 2020-04-07
    • 1970-01-01
    • 2019-06-13
    • 2018-10-01
    相关资源
    最近更新 更多