Vue.js How to define (override) css style in a Component?

守給你的承諾、 提交于 2021-02-11 12:19:22

问题


The default style for the p tag on my page has some bottom margin. My component uses p tags, and accordingly, the p tags in my component text show the corresponding bottom margin. How can I override/define new css style for the p tags in my component. I define my component like this:

 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>
  });

回答1:


Maybe u can try this approach, Pass a variable with the class name to the component

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

Then apply a rule to all p elements inside it, something like this i guess:

    .test p{
      your styles
    }

U can see more here: vue api class and style bindings

I dont know for sure if this was what you wanted, but i gave it a shot :)




回答2:


You have several options - choose your own adventure:

Use a global utility style

Somewhere globally, define a utility class like:

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

Then in your template:

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

Use scoped CSS

If you are using single file components, you can use scoped css:

<template>
  <p class="special-p">hello</p>
</template>

<style scoped>
.special-p {
  margin: 0;
}
</style>

Use inline styles

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

or

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

As an aside, I'd recommend using a CSS reset that globally resets the margins of all elements to 0. Then each component should set the margins as needed for its child elements/components. This may not be reasonable if you already have a large codebase, however.



来源:https://stackoverflow.com/questions/56498003/vue-js-how-to-define-override-css-style-in-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!