3

Is there a way to read data as props in vueJs component and use as value of < style > section?

something like :

<my-component color="red" />

and to use red as a dynamic value inside < style > section of component.

2 Answers 2

4

v-bind can help you with dynamic styling in vue.js as explained [here][1].

The object syntax for v-bind:style is pretty straightforward - it looks almost like CSS, except it’s a JavaScript object. You can use either camelCase or kebab-case (use quotes with kebab-case) for the CSS property names:

HTML

<div v-bind:style="{ color: activeColor, fontSize: fontSize + 'px' }"></div>

vue instance

data: {
  activeColor: 'red',
  fontSize: 30
}

Now activeColor is reactive here, whenever you change activeColor it will change in the HTML/CSS as well. [1]: https://v2.vuejs.org/v2/guide/class-and-style.html#Object-Syntax-1

Sign up to request clarification or add additional context in comments.

6 Comments

I want to use data value inside <style></style> section. like : <style> .className { color: color-data } </style>
@SaJed I dont think that is possible, whats possible is you can have different CSS classes and you can change those classes dynamically as explained here
actually I'm useing datepicker which I need to override its classes to match with my theme color
I have hardcoded this class and it works fine but can't make it flexible: .calendar .cell.highlighted { color: #ffffff; background-color: #4f8fcc!important; } #4f8fcc should set with props value
@SaJed I am using vue-datepicker where I can send color etc in the option variable.
|
-2

Be aware that for CSS properties that have "-" in like background-color you will need to write it slightly different to meet JS object style. Since json object definition format does not allow - in name.

this will work

v-bind:style="{ 'background-color':backgroundColor }"

this will NOT work

v-bind:style="{ backgroundcolor:backgroundColor }"

chaos all the way from Pakistan. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.