【问题标题】:Conditionally target a class with a CSS style in Vue.js在 Vue.js 中有条件地定位具有 CSS 样式的类
【发布时间】:2020-01-10 09:38:32
【问题描述】:

这里有几个关于如何有条件地向元素添加类或如何有条件地向元素添加样式的问题,但我想做的是有条件地为类设置样式。

我有一个带有自己的主题系统的应用程序,它允许用户选择自定义的前景色和背景色。然后我想将这些颜色应用于 quill.js 工具栏按钮。如果我提前知道颜色,我可以在我的风格中添加这样的东西。

.ql-toolbar .ql-stroke {
    stroke: #f00;
}

我什至可以选择在我的容器上抛出一个条件类,并在我的模板中包含多个子样式。

.ql-container.foo {
    .ql-toolbar .ql-stroke {
        stroke: #f00;
    }
}
.ql-container.bar {
    .ql-toolbar .ql-stroke {
        stroke: #b4c;
    }
}

但由于用户可以选择任何 rgb 颜色,我不能这样做。

我也尝试将样式标签写入组件模板,但尝试编译时失败。

现在,为了让事情顺利进行,我只能使用document.querySelector 来访问工具栏并在用户颜色设置更改时更改每个按钮 svg 元素的属性。这是一个丑陋的 hack,它无法处理间歇性样式,例如活动/悬停状态。

有人知道更好的方法吗?

【问题讨论】:

    标签: javascript css vue.js


    【解决方案1】:

    我从this post 学到的答案是使用 CSS 变量,可以通过样式绑定传入。

    <template>
       <div class="container" v-bind:style="{'--toolbarColor': toolbarColor}">
          <!-- quill goes here -->
       </div>
    </template>
    
    <style>
        .ql-toolbar {
            background-color: var(--toolbarColor) !important;
        }
    </style>
    
    <script>
        export default {
            computed: {
                toolbarColor() {
                    return '#f00';
                }
            }
        }
    
    </script>
    
    

    【讨论】:

      【解决方案2】:

      您可以使用styled-components 实现此目的

      或者如果您不想自己设置所有这些,请使用vue-styled-components

      const StyledDiv = styled.div`
        flex: 1;
        ${props =>
          props.justifyContent &&
          css`
            justify-content: ${x => x.justifyContent};
          `};
        ${props =>
          props.padd &&
          css`
            padding: 24;
          `};
      `;
      

      在 vue 模板中

      <styled-div padd justifyContent="flex-start" ></styled-div>
      

      【讨论】:

      • 这只是设置包含组件的样式,它不针对 .ql-stroke
      猜你喜欢
      • 2019-02-21
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 2018-12-15
      • 2017-12-04
      • 2018-04-23
      • 2018-09-22
      • 2013-07-31
      相关资源
      最近更新 更多