【问题标题】:Vue.js How to define (override) css style in a Component?Vue.js 如何在组件中定义(覆盖)css 样式?
【发布时间】:2019-10-23 04:17:03
【问题描述】:

我页面上 p 标记的默认样式有一些底部边距。我的组件使用 p 标签,因此,我的组件文本中的 p 标签会显示相应的下边距。如何为组件中的 p 标签覆盖/定义新的 CSS 样式。我这样定义我的组件:

 Vue.component ('activity-component', {

  props: {

            customer_id:{},
            is_admin:{},         
            isAdmin:{},      
            isKitsActionplan:{},
            ....

    template:
      `<div 
            class="row msDashboard-box"
            style="cursor:default;padding-top:12px; 
                    padding-bottom:12px;"
            >
        ... 
        <p> ... </p>
  });

【问题讨论】:

    标签: vue.js components


    【解决方案1】:

    也许你可以试试这个方法, 将一个带有类名的变量传递给组件

    <my-component v-bind:class="variable with class name"></my-component>
    

    然后将规则应用于其中的所有 p 元素,我猜是这样的:

        .test p{
          your styles
        }
    

    你可以在这里看到更多:vue api class and style bindings

    我不确定这是否是你想要的,但我试了一下:)

    【讨论】:

    • 感谢您的意见。我试试看
    【解决方案2】:

    您有多种选择 - 选择您自己的冒险:

    使用全局实用风格

    在全局某处,定义一个实用程序类,如:

    .u-margin-reset {
      margin: 0;
    }
    

    然后在你的模板中:

    <p class="u-margin-reset">hello</p>
    

    使用作用域 CSS

    如果你使用single file components,你可以使用scoped css

    <template>
      <p class="special-p">hello</p>
    </template>
    
    <style scoped>
    .special-p {
      margin: 0;
    }
    </style>
    

    使用内联样式

    Vue.component('activity-component', {
      template: `<p style="margin:0;"></p>`,
    });
    

    Vue.component('activity-component', {
      computed: {
        myStyle() {
          return {
            margin: 0,
          };
        },
      },
      template: `<p :style="myStyle"></p>`,
    });
    

    顺便说一句,我建议使用 CSS 重置,将所有元素的边距全局重置为 0。然后每个组件应根据需要为其子元素/组件设置边距。但是,如果您已经拥有庞大的代码库,这可能不合理。

    【讨论】:

    • 感谢大卫提供的详细信息。不幸的是,我无法将类添加到组件内的 p 标记中,因为它们是由编辑器动态生成的。但是,我将尝试以编程方式更改 watch 中的 p 标签——希望这会奏效。目前,我使用了一种解决方法——我将所有这些 p 标签放在一个 div 中,并使用 CSS 来更改该 div 中的 p 标签
    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 2019-11-30
    • 2014-04-14
    • 2021-01-20
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多